【问题标题】:How to change dynamically with jquery the background of a div in a site made in wordpress?如何使用jquery动态更改用wordpress制作的网站中div的背景?
【发布时间】:2023-03-20 22:55:01
【问题描述】:

我有一个用 wordpress 制作的网站。网站的每个页面都有一个动态标题,其中 div 的背景每 6 秒随着淡入效果变化一次

我编写的代码在主页上运行良好,但在其他页面中有错误。

我正在获取网站 url 以连接两个字符串:网站 url 和图像名称。因此,使用 jquery 每六秒更改一次背景图像。

问题是内部页面中的 url 采用了所有路径。示例:

在主页中,网址完美地给了我这个结果:“localhost/sitepage”+“wp-content/uploads/2019/05/slider_1.1.png”=“localhost/sitepage/wp-content/uploads /2019/05/slider_1.1.png"

在其余页面中给了我下一个结果:“localhost/sitepage/about/localhost/sitepage/wp-content/uploads/2019/05/slider_1.1.png”

作为“localhost/sitepage/about/”当前页面与我想要的结果连接 localhost/sitepage/wp-content/uploads/2019/05/slider_1.1.png

这是我的代码:

var pageURL = jQuery(location).attr("href");

var img = pageURL+"wp-content/uploads/2019/05/slider_1.1.png";
var img2 = pageURL+"wp-content/uploads/2019/05/slider_1.1.png"; 

var interval = setInterval(function() { 

if(img == img2){


img=pageURL+"wp-content/uploads/2019/05/slider_1.png";

}else{

img=pageURL+"wp-content/uploads/2019/05/slider_1.1.png";

}

console.log(img);
jQuery('#headerhome').fadeTo('slow', 0.3, function()
{
   jQuery(this).css('background-image', 'url(' + img + ')');
}).delay(2500).fadeTo('slow', 1);   

当函数 console.log 打印 img 变量中的值时,完美地显示了我想要的 url:

localhost/sitepage/wp-content/uploads/2019/05/slider_1.1.png

但是在浏览器控制台出现如下错误

错误 404 获取 localhost/sitepage/about/localhost/sitepage/wp-content/uploads/2019/05/slider_1.1.png

我能做什么?

【问题讨论】:

  • 你可以用http://'url(http://' + img + ')'开始URL

标签: javascript jquery wordpress


【解决方案1】:

目前您的 pageURL 显示整个 url,其中包括“关于”永久链接。由于 Wordpress 图像文件位于域的“wp-content”文件夹之外,因此您需要的是一个没有永久链接的静态域名(例如“关于”)。

我假设您希望 pageURL 在 localhost 上测试时显示“localhost/sitepage”,而在生产站点上显示“www.example.com”。

如果是这样,试试这个?

var url = window.location.href; 
var hostname = (new URL(url)).hostname; //returns either 'localhost' or 'www.example.com';
var pageURL = (hostname === 'localhost')? 'localhost/sitepage':'www.example.com';

...

【讨论】:

    【解决方案2】:

    将您的 pageURL 更改为以下内容:

    var pageURL = jQuery(location).attr("href");
    

    到

    var pageURL = document.location.href;
    

    【讨论】:

      猜你喜欢
      • 2011-08-12
      • 2013-09-04
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 2014-08-06
      • 2016-05-06
      • 2020-10-09
      相关资源
      最近更新 更多