我有一个div
我想为使用 PrototypeJS 添加新样式。但是下面的脚本不起作用。它有什么问题?
<div class='exercise-main'>
</div>
$$('.exercise-main').setStyle({
backgroundColor: '#900',
fontSize: '12px'
});
我有一个div
我想为使用 PrototypeJS 添加新样式。但是下面的脚本不起作用。它有什么问题?
<div class='exercise-main'>
</div>
$$('.exercise-main').setStyle({
backgroundColor: '#900',
fontSize: '12px'
});
该$$
函数返回一个包含所有匹配元素(如果有)的数组。setStyle
是元素方法,而不是数组方法。
这里有几个选项。
如果您只期望匹配一个元素,这将起作用。
$$('.exercise-main')[0].setStyle({color:'red'});
如果你想在每个匹配的元素上设置样式,这些都可以。它们本质上是一样的。
$$('.exercise-main').each(function(element) {
element.setStyle({color: 'red'});
});
或者
$$('.exercise-main').invoke('setStyle', {color:'red'});
当然,如果你的元素有一个 id,你可以使用这个$
函数来找到那个元素。这不同于$$
您不传递选择器字符串,而只是传递id 的字符串(即没有'#')。此外,这仅返回元素或 null - 而不是数组 - 因此您可以直接从返回的值使用元素方法,类似于您最初尝试的方法。
$('myElementId').setStyle({color:'red'});