繁体   English   中英

如何更改属性值的一部分

[英]how to alter a portion of a value of an attribute

我有点棘手。 我正在尝试仅更改分配给样式的字符串的一部分。 我想使用js将两个渐变子句中的50%更改为不同的值,而不必在js中创建整个字符串。

setAttribute结合使用某种正则表达式交换吗?

<a class="item" id="bob" style="
background-image:-moz-linear-gradient(0deg, rgb(0, 255, 0) 0%, rgb(250, 250, 5) 50%, rgb(252, 3, 3) 100%);
background-image:-webkit-linear-gradient(0deg, rgb(0, 255, 0) 0%, rgb(250, 250, 5) 50%, rgb(252, 3, 3) 100%);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00ff00',endColorstr='#fc0303',GradientType=1);">MYtext</a>

啊!

var el = document.getElementById('bob');
el.setAttribute('style', el.getAttribute('style').replace('50%', '30%'));

但这会更好:

var el = document.getElementById('bob');
el.style.backgroundImage = el.style.backgroundImage.replace(/50%/g, '30%');

style属性是一个对象,而不是字符串。 因此,您必须执行以下操作:

var bob = document.getElementById('bob');

var background = bob.style.backgroundImage;

if (background) {
    bob.style.backgroundImage = background.replace('50%','70%');
}

如果愿意,还可以在style对象上使用setAttribute

bob.style.setAttribute('backgroundImage' ...

但是在处理style对象时, setAttribute在IE上无法可靠地工作(或以不同方式工作)。 只需使用更短,更可靠的对象访问语法即可:

bob.style.backgroundImage = ...

请参阅: http//www.quirksmode.org/dom/w3c_core.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM