0

我正在使用此脚本根据屏幕宽度加载小图像或大图像。

    <script>
var jt_width = screen.width;
//var jt_height = screen.height;
if (jt_width < 361) {document.write('<div class="small-image"><img src="http://www.example.com/small-image.jpg" alt="small image alt"></div>') } else { document.write('<div class="large-image"><img src="http://www.example.com/large-image.jpg" alt="large image alt"></div>')};
</script>

缺点是在手机上当有人从纵向到横向时它不会即时改变,我想使用 jquery 来做到这一点。

我在网上阅读了有关使用 window.outerWidth 或 .width() 等不同可能性的信息,我了解到 .width() 是浏览器兼容性方面的最佳解决方案。

我想将上面的脚本转换为 jquery 版本,但由于我对 javascript 几乎一无所知,所以我不知道该怎么做。这就是我所拥有的

function load(){
    w.value = $(window).width();
    h.value = $(window).height();
}

如何使用 jquery 获得相同的输出?

4

2 回答 2

0

您的新脚本无助于脚本的响应性。您需要添加一个侦听器:

<script>
var jt_width = screen.width;
function doAThing() {
  if (jt_width < 361) {
    document.write('<div class="small-image"><img src="http://www.example.com/small-image.jpg" alt="small image alt"></div>') } else { document.write('<div class="large-image"><img src="http://www.example.com/large-image.jpg" alt="large image alt"></div>')
  };
}

doAThing();
window.addEventListener('resize', doAThing);
</script>

编辑:我很确定“调整大小”可以很好地进行定向,但是如果您对其进行测试并且效果不佳,您也可以orientationchange在该函数上添加一个侦听器:

window.addEventListener('orientationchange', doAThing);

于 2017-02-16T02:48:35.793 回答
0

这是一个使用 jquery 的实现:

$( window ).resize( function ( ) { 
     var width = $( window ).width( );
     var height=$( window ).height( );
     /**on resize you can change your content or code based on your condition*/
});
/*This event will be triggered when the window size will change */
于 2017-02-16T02:54:05.747 回答