jQuery可以在控制台中使用,但不能在链接的js文件中使用 [英] jquery works in console, but not in linked js file
本文介绍了jQuery可以在控制台中使用,但不能在链接的js文件中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用jQuery脚本根据其尺寸添加类(纵向或横向).然后,我使用jQuery将图像垂直居中.当我将脚本粘贴到控制台中时,该脚本可以很好地工作,但是当我将其链接到文档头中时,该脚本却无法正常工作.这是我的代码:
I am using a jQuery script to add a class (portrait or landscape) depending on their dimensions. Then I am using jQuery to center the image vertically. The script works perfectly when I past it into the console, but not when I link it in the document head. Here is the code I have:
jQuery( document ).ready(
function() {
jQuery(".imgResize").each( function () {
var $this = jQuery(this);
if ( $this.width() > $this.height() ) {
$this.addClass("landscape");
} else if ( $this.width() < $this.height() ) {
$this.addClass("portrait");
} else {
}
var $h = $this.height();
$this.css('margin-top', + $h / -2 + "px");
});
});
什么会导致此问题?
推荐答案
您需要等待图像被加载
jQuery(document).ready(function () {
jQuery(".imgResize").on('load', function () {
var $this = jQuery(this);
if ($this.width() > $this.height()) {
$this.addClass("landscape");
} else if ($this.width() < $this.height()) {
$this.addClass("portrait");
} else {
}
var $h = $this.height();
$this.css('margin-top', +$h / -2 + "px");
});
});
这篇关于jQuery可以在控制台中使用,但不能在链接的js文件中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文