且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以检查 CSS 属性是否对 jQuery 有效吗?

更新时间:2022-10-23 07:48:00

您可以创建一个新元素并将您的 CSS 应用到它.您读取初始值,将您的 css 应用于此元素并立即再次读取该值.如果新值等于初始值,则您的 css 有效(因为它已成功应用于元素).

var div = $("
");var _old = div.css(属性);div.css(属性,值);var _new = div.css(属性);var 有效 = _old!=_new;//如果 (_old != _new),则规则已成功应用console[valid?"log":"warn"](`${property}:${value} 是 ${valid?"":"not"} 有效!`);

小提琴示例

I'm building a simple CSS editor and I want to let the user to edit CSS properties of an element or to add a new one.

Before applying the new CSS property to the element, I want to check if the property is valid.

Do you know a simple way to check if a CSS property/value is valid with jQuery?

UPDATE:

Example:

$('#some-element').css('margin','10px'); //this is valid and it will be applied
$('#some-element').css('margin','asds'); //this is not valid and it will not be applied

How to check, before applying the property, that margin: asds; is not valid?

You can create a new element and apply your CSS to it. You read the initial value, apply your css to this element and immediately read the value again. If the new value does not equal the initial value, your css is valid (because it has been successfully applied to the element).

var div = $("<div>");
var _old = div.css(property);
div.css(property,value);
var _new = div.css(property);
var valid = _old!=_new;
// if (_old != _new), the rule has been successfully applied
console[valid?"log":"warn"]( `${property}:${value} is ${valid?"":"not"} valid!` );

Example fiddle