javascript - JQuery 如何使表单的一部分在聚焦时突出显示?

标签 javascript jquery css

我有一个表格,它被分成由 div 分隔的部分,例如:

<form>
<div>
   Account Details
</div>
<div>
Personal Details
</div>
<div>
...etctec
</div>

</form>

我希望当有人突出显示或关注 div 中的任何元素时,相关的 div 会使用 css 突出显示。考虑一下我已将许多处理程序应用于此表单上的某些输入元素这一事实。

最佳答案

你可以试试:

$('input').focus(
    function(){
        // adds the 'highlight' class to the parent
        $(this).closest('div').addClass('highlight');
    });

与:

$('input').blur(
    function(){
        // removes the 'highlight' class from the parent so only one highlight is ever visible.
        $(this).closest('div').removeClass('highlight');
    });

并在 CSS 中定义 highlight 类:

.highlight {
    background-color: #ffa;
}

JS Fiddle demo ,请注意,在演示中,我使用 fieldset 而不是 div 来包装各种 labelinput 元素,除此之外的原理完全相同。

更新了演示以增加美观:Revised JS Fiddle .


编辑以回应 OP 的问题:

Thats great - however theres a little problem with this code i.e that if ever an input within a div loses focus the div is shown as unhighlighted. Is there a way so that a div remains focus until an input element in another div is focused upon which the parent of the focused div would then get highlighted

是的,假设我没听错,那很简单:

$('input').focus(
    function() {
        $(this)
            .closest('form')
            .find('.highlight')
            .removeClass('highlight');
        $(this).closest('fieldset').addClass('highlight');
    });

JS Fiddle demo .

关于javascript - JQuery 如何使表单的一部分在聚焦时突出显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5611339/

相关文章:

javascript - 如何多次调用一个动画函数

javascript - 更新元素之间的距离

css - IE8 CSS Hack - 最好的方法?

javascript - 在 Node.js 服务器运行时运行命令?

javascript - .next() 在 Each 循环中未定义

javascript - 为什么 _sortBy 不适用于大写字母?

javascript - 最后只出现一次 '%' 的接受号码的正则表达式

html - 如何使语义用户界面中的固定顶部菜单不覆盖内容

javascript - 是否有一个 Javascript 事件可以根据用户输入不断更新 DOM?

c# - CSS 和 JS 文件未呈现