javascript - jQuery获取图片尺寸为什么会有高度无宽度?

查看:140
本文介绍了javascript - jQuery获取图片尺寸为什么会有高度无宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

jq获取图片有高度没宽度。图片是控制台输出。

页面地址是http://ao.acg.ac/?p=426,博客程序是wordpress。用于获取图片并限制其宽高的插件如下,控制台数据是这个插件输出的:

<?php
/*
Plugin Name: MMFix
Plugin URI: http://touko.host.smartgslb.com/
Description: 此插件用于修复Modern Metro主题的一系列错误。需和MM-Mod搭配使用。
Author: AozakiOrenji
Version: 0.1
*/
function loadJs(){
    wp_reset_query();
    if(is_single()){
        echo '
            <script src="./jquery.js"></script>
            <script>
                console.log("please wait");
                jQuery(".alignnone:not(.no-border)").each(function(){
                    var img = jQuery(this);
                    console.log("object found, height is " + img.height() + ", height limit is " + jQuery(window).height()*0.55 + ", width is " + img.width() + ", width limit is 500");
                    if(jQuery(this).height() > jQuery(window).height()*0.55){
                        console.log("height is larger than " + jQuery(window).height()*0.55 + ", operating");
                        jQuery(this).height(jQuery(window).height()*0.55);
                    }
                    if(jQuery(this).width() > 500){
                        console.log("width is larger than 500, operating");
                        jQuery(this).width(500);
                    }
                });
                console.log("done.");
            </script>
        ';
    }
}
add_action("get_footer","loadJS");
?>

所以为什么会这样呢。。。

解决方案

事实上,手工运行
jQuery(".alignnone:not(.no-border)").each(function(){console.log(jQuery(this).width());})
的结果:是能拿到的。

然而我打开你页面的时候,不仅宽度拿不到,高度也拿不到:
object found, height is 0, height limit is 358.6, width is 0, width limit is 500

这里有一个大问题,你的脚本在运行到var img = jQuery(this);var img = jQuery(this);`时,图片有开始加载吗?如果图片还未开始加载,那么宽高值就是0。

你需要在图片开始加载之后(只要开始加载文件头就行),才能运行获取图片信息的命令。
JQuery可参考:$(document).ready(function(){}

这篇关于javascript - jQuery获取图片尺寸为什么会有高度无宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆