gpt4 book ai didi

javascript - onload 操作仅在基于 WebKit 的 Chrome 上的同一页面上运行一次

转载 作者:行者123 更新时间:2023-12-03 12:07:59 27 4
gpt4 key购买 nike

我只是实现了一个jquery代码,让我的图片在div中垂直中间位置,代码如下。

function setImgMiddle(img) {  
var $img = $(img),
$panel = $(img).parent();

var img_width = $img.width(),img_height = $img.height(),
panel_width = $panel.width(), panel_height = $panel.height();

if(panel_width/panel_height < img_width/img_height){
$img.width(panel_width);
$img.css('margin-top', (panel_height - $img.height()) * 0.5);
}
$img.fadeIn(100);
}

我在我的index.html中使用以下代码。

<img id="pic_in" class="lazy" onload="setImgMiddle(this)" src="<?php echo catch_first_image() ?>"  alt="<?php the_title(); ?>"  width="200px"  />

因为我在wordpress中使用了这个,所以它可以解释src和alt的事情

问题是我在同一页面的不同位置有两个引用部分,但是,onload 操作仅触发一次(第一个在前面),第二个不起作用,我在互联网上搜索,他们说我应该先 new a Image() ,但我是初学者,对他们的代码感到有点困惑,并且不理解。所以我需要帮助,谢谢!

最佳答案

您可以在 CSS 中执行此操作,无需 JavaScript:

HTML:

<div class="center_image_box ">
<div class="aligner">
<img src="image.png">
</div>
</div>

CSS:

.center_image_box {
display: inline-block;
height: 60px;
width: 60px;
vertical-align: middle;
position: relative;
border: 1px solid #dedede;
background: white;
box-shadow: 0px 1px 1px #ccc;
padding: 3px;
}

.aligner {
display: block;
font: 0pt/0 a;
height: 60px;
position: relative;
text-align: center;
vertical-align: middle;
width: 60px;
}

.aligner:before {
content: ' ';
display: inline-block;
vertical-align: middle;
height: 100%;
}

.aligner img {
max-width: 100%;
max-height: 100%;
vertical-align: middle;
display: inline-block;
}

对于您的 JavaScript,您需要预加载两个图像:

<script>

function preloadImage(src, callback) {
var image = new Image();
image.src = "image.png";
image.onLoad = function() {
callback(image);
}
}
$(document).ready(function(){

var images = array();
images[] = 'image1.png';
images[] = 'image2.png';

for (var i=0; i<images.length;i++) {
preloadImage(images[i], setImgMiddle);
}

});

</script>

关于javascript - onload 操作仅在基于 WebKit 的 Chrome 上的同一页面上运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25097814/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com