以内联样式删除无效的css属性

Invalid css property gets removed in inline style

本文关键字:css 属性 无效 删除 样式      更新时间:2023-09-26

我在元素中定义了一些内联样式

<div id="box" style="-ms-grid-row:1; background-color: yellow;"></div>

,然后用javascript设置一个样式。

var box = document.getElementById('box');
box.innerHTML += '<br>before: ' + box.getAttribute('style');
box.style.height = '100px';
box.innerHTML += '<br>after: ' + box.getAttribute('style');

,输出变成:

before: -ms-grid-row:1; background-color: yellow;
after: background-color: yellow; height: 100px;
测试http://jsfiddle.net/P7eBN/

浏览器删除了-ms-grid-row属性,我不希望它这样做,因为我正在写一个插件,读取内联风格的-ms-grid-row属性,所以-ms-grid-row需要以某种方式保留。使用jQuery时也是如此。$(box).height(100)

我怎样才能以最好的方式让用户通过样式设置高度。高度,仍然能够读取-ms-grid-row属性之后不知何事?

我正在写一个插件,读取内联样式与-ms-grid-row属性,所以-ms-grid-row需要以某种方式保存。听起来像是数据属性的工作:

<div id="box" data-ms-grid-row="1" style="background-color: yellow;"></div>

你的插件会将其读取为(跨浏览器方式)

box.getAttribute('data-ms-grid-row')

或对于现代浏览器:

box.dataset.msGridRow

这个怎么样?

var box = document.getElementById('box');
box.innerHTML += '<br>before: ' + box.getAttribute('style');
box.setAttribute('style', box.getAttribute('style') + ' height : 100px;');
box.innerHTML += '<br>after: ' + box.getAttribute('style');

当您编写任何CSS样式时,它将被浏览器过滤并应用于元素。比如说,for。,你写这个CSS:

border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;

当你在Chrome开发者工具中检查时,你将只看到-webkit-border-radius: 5px;,而其他将不应用

<<p> 解决方案/strong>

假设您正在为浏览器提供HTML版本,因此您可以使用data-属性。以这种方式发送样式:

style="border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px;"
data-style="border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px;"

现在你读的是data-style,而不是style。最终的代码将类似于:

var box = document.getElementById('box');
box.innerHTML += '<br>before: ' + box.getAttribute('data-style');
box.setAttribute('style', box.getAttribute('style') + '; height : 100px');
box.innerHTML += '<br>after: ' + box.getAttribute('data-style');

我在Internet Explorer 9上尝试了您的页面,属性如预期的那样保留了下来。除ie以外的浏览器会忽略-ms-前缀。因此你不能看到它