从脚本更改src,这取决于浏览器大小

时间:2015-07-08 07:03:39

标签: javascript jquery html src

我的网站有点问题

我试图根据脚本在div中的浏览器大小来改变脚本中的src属性

这是代码的样子



<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>
&#13;
&#13;
&#13;

我试图从脚本中更改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通过使用标记名称来工作,在我的情况下我的脚本是来自div的子...

有没有办法解决它?

NEW

    <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>

我尝试使用上面的代码,但它也不起作用

它只显示宽度编号,但附加功能不执行任何操作

&#34; ASD&#34;是div的id

还有其他的问题吗?

2 个答案:

答案 0 :(得分:0)

设置脚本标记的SRC属性只能进行一次。您已经以编程方式附加了新的脚本标记。

请参阅此回答Changing "src" attribute of <script>

答案 1 :(得分:0)

这个解决方案怎么样:

<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>');
  };