在JSFiddle上运行的简单JQuery脚本,不在我的网站上

在JSFiddle上运行的简单JQuery脚本,不在我的网站上

问题描述:

我正在尝试使用JQuery获取图像的原始宽度,并在CSS进行一些调整,条件是图像的宽度大于700px.

I'm trying to get the original width of an image with JQuery and make some adjustments in the CSS with a condition if an image is wider than 700px.

我使用以下代码来获取图像的宽度:

I used this code to get the width of an image:

var img = new Image();
img.src = $('#imageViewerImg').attr('src');
img.onload = function () {
    var W2 = this.width;
    alert(''+ W2);
}

小提琴

您会看到一个警告框显示图像的宽度,在本例中为1024.在我复制粘贴此代码时,它在我的网站上不起作用.它根本不会显示警报框.我已经正确地包含了JQuery,因为其他JQuery代码可以正常工作,但这只是这个简单的JQuery并没有完成应有的功能.

Fiddle

You can see that an alert box shows the width of the image, in this case 1024. When I copy paste this code, it doesn't work on my website. It simply won't display the alert box. I have JQuery included properly, as other JQuery codes work, it's just this simple piece of JQuery that doesn't do what it's supposed to do.

最后,这是我要创建的功能所需的代码:

At the end, this is the code I need for the functionality I'm trying to create:

var img = new Image();
img.src = $('#imageViewerImg').attr('src');
img.onload = function() {
    var imgWidth = this.width;
}
if($imgWidth > 700) {
    $("#photoHolder").css({"vertical-align":"none","text-align:":"none"});
}

为什么警报框会显示在JSfiddle上而不显示在我自己的PC上?

Why does the alert box show up on JSfiddle but not on my own PC?

同样具有document.ready功能,它仍然无法使用.只是没有执行JQuery.

Also with the document.ready function, it still won't work. The JQuery is simply not being executed.

使用jQuery文档就绪功能,如下所示:

Use the jQuery document ready function like this:

$(document).ready(function(){

});

这是一个常见的错误",包含从jsFiddles复制的代码.

This is a common "bug" with code that is copied from jsFiddles.