使用JQuery检查元素是否有边框

Use JQuery to check if element has a border?

本文关键字:边框 是否 元素 JQuery 检查 使用      更新时间:2023-09-26

所以我在玩$(el).css(),试图确定元素是否有边界。我使用.css("border-style", "solid")来设置边界,这很有效,但实际上它设置了4种单独的样式:

border-right-style
border-left-style
border-top-style
border-bottom-style

因此,检查边界有点麻烦,因为你必须做一些类似的事情:

if ($(el).css("border-right-style") == "solid" && $(el).css("border-left-style") == "solid" && ...) {}

简单地检查$(el).css("border-style") != ""是不起作用的,因为border-style总是等于"。

有更优雅的方法吗?

border-style是Shorthand,你不能把它们放在一起,所以你必须把它们分开,因为根据Jquery CSS文档

Shorthand CSS properties (e.g. margin, background, border) are not supported.
For example, if you want to retrieve the rendered margin, 
use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.

如果您想知道是否设置了4个属性,那么是的,您必须检查4个属性。尽管我会缓存选择器。

$el = $('a');
if ($el.css("border-right-style") == "solid" && $el.css("border-left-style") == "solid" && $el.css("border-top-style") == "solid" && $el.css("border-bottom-style") == "solid") 
{
    alert('yay');
}

jsFiddle

我不知道是否可以做你正在尝试的事情。DOM只为内联分配的元素或脚本中的元素提供样式。它不会显示它是否从CSS声明中继承了诸如border之类的样式。

您仍然需要测试属性,但这会使其更加抽象。。。

function check(sel, prop) {
    var i, property, $o = $(sel), directions = ["left", "right", "top", "bottom"];
    for (i = 0; i < directions.length; i++) {
        property = $o.css(prop + '-' + directions[i] + '-style');
        if (property !== 'solid') {
             return false;
        }
    }
    return true;
}

它可以显示继承的CSS文件的样式值。。。。

alert($("选择器").css("边框底部颜色"));