javascript - 通过 JS 获取基于类的 CSS 属性不起作用

标签 javascript jquery html css size

我有 JS 代码,我在其中尝试确定图像的大小是通过 CSS 还是使用宽度/高度属性显式设置的。如果是这样,我尊重设置的大小,否则我自己执行代码来调整图像的大小。这是代码。它使用一些 jQuery,所以 image 是一个 jQuery 对象,image[0] 访问实际的 DOM 元素:

if (image.attr('height') == undefined && image[0].style.height.length == 0) {
    image.data("explicit_height", false);
    //Do stuff to the image size here
} else {
    image.data("explicit_height", true);
}

// ...SAME FOR WIDTH...

我面临的问题是,只要使用高度/宽度或样式属性,这段代码就可以正常工作。当通过 CSS 选择器(例如类选择器)设置高度/宽度时,代码不起作用。代码在窗口加载时执行。

有人知道为什么会发生这种情况以及如何解决它吗?

最佳答案

您必须使用 getComputedStylecurrentStyle 来获取样式表中设置的样式(后者适用于早期版本的 IE。) style将只返回内联样式属性。

(image.getAttribute('height') == null
 && ((window.getComputedStyle(image)||image.currentStyle)['height']) == '0px') ?
    //do stuff
:
    //do other stuff

您还可以将该语句的计算映射到一个函数对象:

function foo() { image.data("explicit_height", false) }
function bar() { image.data("explicit_height", true) }

var bool = ( image.getAttribute('height') == null
 && ((window.getComputedStyle(image)||image.currentStyle)['height']) == '0px' ),
fn = {
    true:foo,
    false:bar
}[bool]();

您需要尝试使用 image.getAttribute('height') == null 和后面的语句,因为它们基于浏览器中的默认值,这可能是不同(我只在 Firefox 26 for Mac 10.9 上测试过,没有 height 属性的默认值为 null 并且样式表中没有声明 height 的默认值为 0px .)

更新的答案

看看这个 jsfiddle :

var image = document.getElementsByTagName('img')[0];

function foo() { image.setAttribute("name", "foo") }
function bar() { image.setAttribute("name", "bar") }

var styleSheets = document.styleSheets;

function isHeightDefinedInStyleSheets(tag) {
    for(i in styleSheets) {
        var rules = styleSheets[i]['cssRules'||'rules'];        
        if(rules!==undefined) {
            for(j in rules) {
                if(rules[j]['style']!==undefined&&rules[j].selectorText===tag) {
                    if(parseInt(rules[j]['style']['height'])>0) {
                        console.log(true);
                         return true;   
                    }
                }
            }
        }
    }

    console.log(false);
    return false;
}

var fn = {
    true:foo,
    false:bar
}[!isHeightDefinedInStyleSheets('img') && image.getAttribute('height') == null]();

此函数将检查样式表本身是否存在规则(这不同于 getComputedStyle,它将根据计算值获取元素的样式,而不管该值是否已定义内联或在样式表中等)它的返回值作为键传递,返回值检查 height 是否被内联定义为图像的属性。如果该语句评估为“真”,它将执行对象 fn 中的“真”函数 (foo);否则它将执行 bar

我之前没有处理过 styleSheets 属性,因此代码需要清理很多,但它演示了基本点。此外,如果您有一个 img 元素的集合,您将需要实现一个循环函数来遍历集合中的每个元素。

关于javascript - 通过 JS 获取基于类的 CSS 属性不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21717031/

相关文章:

JQuery:类型错误:对象 0 没有方法 'attr'

javascript - 如何让 Ocrad.js 示例工作

html - 将4个div( child )放在 parent 的 Angular 落

html - ionic 单选按钮验证

javascript - 使用 Angular 将 Google 分析 ID 插入到脚本中

javascript - 在 DIV 中的 Canvas 上获取点击坐标

javascript - 如何从方括号内的对象解析字符串

javascript - 为什么 jQuery.data() 会出现 Raphael svg 路径错误?

javascript - 我如何判断一个元素是否在影子 DOM 中?

php - 文件API上传文件