2

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

<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)

我怎样才能以最好的方式允许用户通过 style.height 设置高度,并且之后仍然能够以某种方式读取 -ms-grid-row 属性?

4

4 回答 4

3

我正在编写一个使用 -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
于 2013-03-28T07:40:50.480 回答
2

那这个呢?

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');
于 2013-03-28T07:39:10.117 回答
1

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

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

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

解决方案

假设您将 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');
于 2013-03-28T07:37:13.990 回答
0

我在 Internet Explorer 9 上尝试了您的页面,并按预期保留了该属性。-ms- 前缀被 Internet Explorer 以外的浏览器忽略。因此你无法看到它。

于 2013-03-28T08:21:14.487 回答