"Syntax error, unrecognized expression" 用于图像的高度和宽度

"Syntax error, unrecognized expression" for height and width on image

我无法使用下面的代码获取图像的高度和宽度。我不断收到 Uncaught Error: Syntax error, unrecognized expression: ...ge/p1010352.jpg.

$('body').on('click', '#view-large', function() {

    // VARIABEL
    var image = $(this).attr('data');
    var image_src = '../blog/images/uploaded/large/p1010352.jpg';
    var image_height = $(image_src).naturalHeight();
    var image_width = $(image_src).naturalWidth();
    console.log(image_height);

    // VISA & CSS
    $('.blog-image-view').show().css({
        'background-image': 'url(' + image_src + ')',
        'margin-top': '-' + (image_height / 2) + 'px',
        'margin-left': '-' + (image_width / 2) + 'px',
        'height': image_height + 'px',
        'width': image_width + 'px'
    });

});

这段代码的目的,是点击 link 并获取所选图像的大图(but in the demo,我只使用 link - 同样的问题) .我已经用 heightwidthclientHeightclientWidth 进行了测试。同样的错误。

等问题解决后,我会把上面代码中的link删掉!

我该如何解决这个问题?

您似乎在尝试将图像源用作选择器,并以此方式动态确定图像的高度和宽度。这是行不通的,因为 URL 不是有效的 jQuery 选择器(有充分的理由;这具有严重的安全隐患)。

您要做的是在服务器端获取高度和宽度,或者在隐藏的 div 中加载图像,然后确定其尺寸。

这是因为您正在做的 $(url).naturalHeight() 不是有效的选择器,请添加 anm id 或 class 或要获取的图像标签..

我添加了一个 ID 为 demo<img> 标签。

此外 .naturalHeight() 不是有效函数,您可以使用 .prop() 来实现同样的效果

$(document).ready(function() {
    
    $('body').on('click', '#view-large', function() {
    
        // VARIABEL

        var image = $(this).attr('data');
        var image_src = 'http://nhagyavi.myftp.org/blog/images/uploaded/large/p1010352.jpg';
        $('#demo').attr('src',image_src);
        var image_height = $('#demo').prop('naturalHeight');
        var image_width = $('#demo').prop('naturalWidth');
        console.log(image_height);
    
        // VISA & CSS
        $('.blog-image-view').show().css({
            'background-image': 'url(' + image_src + ')',
            'margin-top': '-10px',
            'margin-left': '-10px',
            'height': image_height + 'px',
            'width': image_width + 'px'
        });
    
    });

});
.blog-image-view {
    background-color: #222222;
    display : none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="javascript:void(0)" id="view-large" data="p1010352.jpg">View</a>

<div class="blog-image-view"></div>
<img id='demo' src=''/>

您的代码中的错误是您将 url 作为 class 选择器传递。

这是一个修复方法:

更改以下内容:

var image_src = 'http://nhagyavi.myftp.org/blog/images/uploaded/large/p1010352.jpg';
var image_height = $(image_src).naturalHeight();
var image_width = $(image_src).naturalWidth();

var image_src = 'http://nhagyavi.myftp.org/blog/images/uploaded/large/p1010352.jpg';
var temp_img = document.createElement("img");
temp_img.src = image_src;
var image_height = $(temp_img).height();
var image_width = $(temp_img).width();