简体   繁体   English

“裁剪”图像的脚本间歇性地运行。

[英]Script to “crop” images runs intermittently.

I'm using some javascript to cause images to appear to be cropped. 我正在使用一些JavaScript来使图像看起来被裁剪。 I essentially find images with a height over 400px, find how many pixels over 400px they are, split it, and make those negative margins on the top and bottom. 我基本上找到高度超过400像素的图像,找到超过400像素的像素数,将其分割,并在顶部和底部形成负边距。 I then wrap the image in a div that acts as a frame, behind which the image sits 然后我将图像包装在一个div中,该div充当一个框架,图像位于框架后面

For some reason, the script runs occasionally. 出于某种原因,脚本偶尔会运行。 Some times, it will correctly crop all .featured-image img images over 400px in height (there is only one featured images on the home page, and it requires cropping). 有时,它会正确裁剪超过400px高度的所有.featured-image img图像(主页上只有一个特色图像,需要裁剪)。 Other times, the script doesn't detect any such image and thus does no cropping. 其他时候,脚本不会检测到任何此类图像,因此不会进行裁剪。

I run the script inside a $(document).ready() call, so I'm not sure what's causing what seems to be a race condition. 我在$(document).ready()调用中运行脚本,所以我不确定是什么导致了什么似乎是竞争条件。

Links 链接

The site: http://new.technoheads.org/ (Refresh a few times to see what I mean) 网站: http//new.technoheads.org/ (刷新几次,看看我的意思)

The script: http://new.technoheads.org/wp-content/themes/Technoheads-Theme/js/app.js (lines in question are 13-20) 脚本: http//new.technoheads.org/wp-content/themes/Technoheads-Theme/js/app.js (有问题的行是13-20)

Incorrect: http://technoheads.org/grabs/DK6.png 不正确: http//technoheads.org/grabs/DK6.png

Correct: http://technoheads.org/grabs/GQP.png 正确: http//technoheads.org/grabs/GQP.png

You're checking the height properties of the image, which don't necessarily exist on document ready (document ready doesn't mean images have been loaded). 您正在检查图像的height属性,这些属性不一定存在于文档就绪中(文档就绪并不意味着已加载图像)。 Either bind that function inside $(window).load() , or an $('img').load() function. $(window).load()$('img').load()函数中绑定该函数。

Example: 例:

$(".featured-image img").load(function() {
    var $e = $(this);

    if ( $e.height < 400 ) return;

    var overflow = featuredHeight - $e.height();
    var top      = overflow / 2;
    var bottom   = overflow / 2;

    if ( overflow % 2 == 1 ) top++;

    $e.css({
        "margin-top": top + "px", 
        "margin-bottom": bottom + "px"
    });
});

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

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