没有onclick的Javascript高亮效果

Javascript highlight effect without onclick

本文关键字:高亮 Javascript onclick 没有      更新时间:2023-09-26

有没有一种方法可以更改div背景色(高亮显示),而不必在每次输入onclick中调用函数?

这是我的Javascript函数:

<script type="text/javascript">
function highlight(element) {
    element.parentNode.style.backgroundColor = '#FF9900';
}
function removeHighlight(element) {
    element.parentNode.style.backgroundColor = '';
}
</script> 

这是HTML:

<div class="form-item">
<label>Title:</label>
<input class="form-text Title"
       type="text"
       onblur="removeHighlight(this);"
       onfocus="this.value='';highlight(this);"
       onselect="this.value='';"
       onclick="this.value='';highlight(this);"
       value="english"
       name="Title">
<input class="form-text translations"
       type="text"
       onselect="this.value='';"
       onclick="this.value='';"
       value="translate"
       name="title_translate">
</div>

在这里,我必须在每次输入onclick或onselect中调用该函数,这有时会与页面上的其他Javascript函数冲突。

您可以匿名将其绑定到特定元素:

document.getElementById('foo').onclick = function() {
  this.parentNode.style.backgroundColor = '#FF9900';
}

但是,您将被迫使用id(比编写20次相同的onclick代码要好)。

如果您使用像jQuery这样的JavaScript库,则此代码可以简化很多:

$('div.form-item input').select(function() {
  $(this).parent().css('background-color', '#FF9900');
});
$('div.form-item input').blur(function() {
  $(this).parent().css('background-color', 'auto');
});

这将处理<div>中的所有<input>元素。不需要HTML中的任何内容。这一切都是在JS端完成的。