Simple JQuery script working on JSFiddle, not on my site

后端 未结 4 636
有刺的猬
有刺的猬 2021-01-20 03:02

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

相关标签:
4条回答
  • 2021-01-20 03:07

    your variable $imgWidth is undeclared in your code, and imgWidth will not have scope outside your function.

    try:

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

    Use the jQuery document ready function like this:

    $(document).ready(function(){
    
    });
    

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

    0 讨论(0)
  • 2021-01-20 03:20

    Try it like this:

    var img = new Image();
    img.onload = function () {
        var W2 = this.width;
        if(W2 > 700) {
            var photoHolder = document.getElementById("photoHolder");
            photoHolder.style.verticalAlign = 'none';
            photoHolder.style.textAlign = 'none';
        }
    }
    img.src = document.getElementById('imageViewerImg').src;
    

    Also, open the console and check for errors, check that you only have one element with that ID etc.

    0 讨论(0)
  • 2021-01-20 03:22

    Use that to be sure that your code will be executed after the html loading.

    $(document).ready(function(){
        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"});
        }
    });
    
    0 讨论(0)
提交回复
热议问题