如果元素是由外部 javascript 脚本生成的,则答案会复杂得多。您需要先找到元素,因此 by id 和 class 方法将不起作用,除非它们已经有一个 - 请参阅下面的 type 解决方案。
通过id查找:
以下是首选,您需要在输入提交中添加一个 id,例如<input type="submit" id="submit"> 引用它:
// CHANGE SUBMIT STYLE
var foo = document.getElementById('submit');
foo.onmouseover = function() {this.style.borderColor='#000000'; this.style.color='#000000';}
foo.onmouseout = function() {this.style.borderColor='#888888'; this.style.color='#888888';}
foo.onclick = function() {this.style.borderColor='#000000'; this.style.color='#000000';}
但以下也应该有效:
通过class查找:
您需要指定一个类,例如<input type="submit" class="submit"> 在这种情况下。
getElementsByClass 不寻找 type,它寻找 class。
<script type="text/javascript">
function getElementsByClass(node,searchClass,tag) {
var classElements = new Array();
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("\b"+searchClass+"\b");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
// CHANGE SUBMIT STYLE
var foo = getElementsByClass(document.body, 'submit', 'input')[0];
foo.onmouseover = function() {this.style.borderColor='#000000'; this.style.color='#000000';}
foo.onmouseout = function() {this.style.borderColor='#888888'; this.style.color='#888888';}
foo.onclick = function() {this.style.borderColor='#000000'; this.style.color='#000000';}
</script>
通过type查找:
如果您使用以下内容,您可以通过type 找到:
function getElementByType(node,type,tag) {
var els = node.getElementsByTagName(tag);
for (var x=0, x<els.length; x++) {
if (els[x].type && els[x].type.toLowerCase() == type) {
return els[x]
}
}
}
var foo = getElementByType(document.body, 'submit', 'input')
...
我会做的是:
<div id="externalElms">
(<script> here)
</div>
然后使用var foo = getElementByType(document.getElementById('externalElms'), 'submit', 'input'),这样就不必遍历页面上的每个元素。