繁体   English   中英

Chrome在刷新后不执行jquery功能,但在单击链接时执行

[英]Chrome doesn't execute jquery function after refresh but does when link is clicked

您好,我还有另一个奇怪的问题。 我有一个按比例调整图像大小的jquery函数。 但是,当我刷新页面时,它在chrome上无法正常工作。 让我解释。 如果您点击主页链接,它将起作用,并且所有图像都会调整大小。 如果刷新页面,则某些图像或全部图像均不会调整大小。 这仅在Chrome中发生。 它不会在Firefox中发生。

这是jQuery

$.fn.imageResize = function(options) {
    var settings = {
        width: 400,
        height: 222
    };

    options = $.extend(settings, options);

    return this.each(function() {
        var $element = $(this);
        var maxWidth = options.width;
        var maxHeight = options.height;
        var ratio = 0;
        var width = $element.width();
        var height = $element.height();

        if ( width > maxWidth ) {
            ratio = maxWidth / width;

            $element.css("width", maxWidth);
            $element.css("height", height * ratio);
        }

        if (height > maxHeight) {
            ratio = maxHeight / height;

            $element.css("height", maxHeight);
            $element.css("width", width * ratio);
        }
    });
}

我的标题包含必要的内容

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="/app/core/views/js/image-resize.js">   </script>

然后我在页面上调用该函数

<script type="text/javascript">
    $(document).ready(function() {
        $('img').imageResize();
    });
</script>

<img src="" alt="">

因此,如果通过链接加载页面,代码将起作用,并且图像将按比例调整大小。 如果按f5或“刷新”按钮,则该代码将不起作用,并且图像将以其原始大小显示。

有没有办法确保代码可以在chrome上正确执行?

您调用.imageResize()时间过早,因为$(document).ready()在内容加载完成之前触发。 该方法可以运行,但是找不到有效的目标。

将其绑定到窗口load ,很可能会按预期工作:

$(window).on('load', function(){
   $('img').imageResize();
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM