我的网站出了点小问题
我试图改变src属性从我的脚本基于浏览器的大小,脚本是在div
代码如下
<div style="margin: 15px 0px 0px; display: inline-block; text-align: center;">
<script id="world" type="text/javascript" src="http://localtimes.info/world_clock2.php?&cp1_Hex=ffd700&cp2_Hex=000000&cp3_Hex=000000&fwdt=72&ham=0&hbg=0&hfg=0&sid=0&mon=0&wek=0&wkf=0&sep=0&widget_number=21000&lcid=SNXX0006,USNY0996,UKXX0085,ASXX0112,HKXX0001"></script>
</div>
我试图改变src从脚本src本身包含的宽度(在脚本中的fwdt值)的小部件,我想根据浏览器的大小改变
我想用下面的代码解决我的问题
<script>
var w = window.innerWidth;
if (w>991) {
document.getElementById("demo").innerHTML = "Width: " + w ;
$('#world').attr('src','http://localtimes.info/world_clock2.php?&cp1_Hex=ffd700&cp2_Hex=000000&cp3_Hex=000000&fwdt=200&ham=0&hbg=0&hfg=0&sid=0&mon=0&wek=0&wkf=0&sep=0&widget_number=21000&lcid=SNXX0006,USNY0996,UKXX0085,ASXX0112,HKXX0001');
}
else if (w<991) {
document.getElementById("demo").innerHTML = "Width: " + w ;
$('#world').attr('src','http://localtimes.info/world_clock2.php?&cp1_Hex=ffd700&cp2_Hex=000000&cp3_Hex=000000&fwdt=100&ham=0&hbg=0&hfg=0&sid=0&mon=0&wek=0&wkf=0&sep=0&widget_number=21000&lcid=SNXX0006,USNY0996,UKXX0085,ASXX0112,HKXX0001');
};
</script>
但是,我的代码没有对脚本src
做任何事情。我从互联网上找到的是创建脚本本身,其中使用appendChild…但是,appendChild通过使用标签名来工作,在我的情况下,我的脚本是child fromdiv…
有办法解决吗?
新 <script>
var w = window.innerWidth;
if (w>991) {
document.getElementById("demo").innerHTML = "Width " + w;
$('#asd').append('<script type="text/javascript" src="http://localtimes.info/world_clock2.php?&cp1_Hex=ffd700&cp2_Hex=000000&cp3_Hex=000000&fwdt=100&ham=0&hbg=0&hfg=0&sid=0&mon=0&wek=0&wkf=0&sep=0&widget_number=21000&lcid=SNXX0006,USNY0996,UKXX0085,ASXX0112,HKXX0001"></script>');
}
else if (w<991) {
document.getElementById("demo").innerHTML = "Width " + w;
$('#asd').append('<script type="text/javascript" src="http://localtimes.info/world_clock2.php?&cp1_Hex=ffd700&cp2_Hex=000000&cp3_Hex=000000&fwdt=200&ham=0&hbg=0&hfg=0&sid=0&mon=0&wek=0&wkf=0&sep=0&widget_number=21000&lcid=SNXX0006,USNY0996,UKXX0085,ASXX0112,HKXX0001"></script>');
};
</script>
我尝试使用上面的代码,但它不太工作
它只显示宽度数字,但append函数不做任何事情
"asd"是div的id
有其他解决方案吗?
设置脚本标签的SRC属性只能设置一次。您可以通过编程方式添加新的脚本标签。
查看此答案更改"src"script>
这个解决方案如何:
<div id="container" style="margin: 15px 0px 0px; display: inline-block; text-align: center;">
<script id="world" type="text/javascript" src="<your src>"></script>
</div>
var w = window.innerWidth;
$("#demo").html("Width: " + w);
$("#world").remove();
if (w > 991) {
$('#container').append('<script id="world" type="text/javascript" src="<your src>"></script>');
}
else if (w < 991) {
$('#container').append('<script id="world" type="text/javascript" src="<your src>"></script>');
};