jquery行悬停和单击事件

标签 jquery css

我试图突出显示悬停时的一行,这对我来说效果很好。同时,我想在单击时突出显示悬停的行。下面是我到目前为止的代码:

        $(".simplehighlight").hover(function() {
            $(this).children().css('backgroundColor', '#ffdc87');
        },
        function() {
            $(this).children().css('backgroundColor', '#fff');
        }); 

如果我将点击事件设置为与上面相同,则它不起作用。

        $(".simplehighlight").click(function() {
            $(this).children().css('backgroundColor', '#ffdc87');
        },
        function() {
            $(this).children().css('backgroundColor', '#fff');
        }); 

关于如何实现这一目标有什么建议吗?

最佳答案

更新:这是一个使用 CSS 类的更好版本:

$(".simplehighlight").click(function() {
    $(this).toggleClass('clicked');
    // comment the following line if you don't want to dehighlight other rows
    $(this).siblings().removeClass('clicked');
});

$(".simplehighlight").hover(function() {
    $(this).children().css('backgroundColor', '#ffdc87');
}, function() {
    $(this).children().css('backgroundColor', '');
});

CSS 在哪里:

.simplehighlight {
    background-color: #fff;
}

.clicked {
    background-color: #ffdc87;
}

DEMO


旧答案: 可以工作,但不必要的复杂。

click 只接受一个回调,而不是两个。您可以使用 data 来检查行是否被单击:

$(".simplehighlight").click(function() {
    var clicked = $(this).data('clicked');
    $(this).data('clicked', !clicked);
    if(clicked) {
        $(this).children().css('backgroundColor', '#fff');
    }
    else {
        $(this).children().css('backgroundColor', '#ffdc87');
    }
});

然后,为了更改 mouseleave 上的调用者,请检查 clicked 值:

$(".simplehighlight").hover(function() {
    $(this).children().css('backgroundColor', '#ffdc87');
},
function() {
    if(!$(this).data('clicked')) {
        $(this).children().css('backgroundColor', '#fff');
    }
}); 

Working DEMO

关于jquery行悬停和单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4472715/

相关文章:

javascript - Bootstrap 模式 : background jumps to top on toggle

jquery - 将 JSON 对象从 Python 脚本发送到 jQuery?

css - 在两个固定的 div 元素之间创建一个滚动的 div

html - 如何修复 div 悬停以正确显示而不丢失边?

html - contert_placeholder 上的内容与页脚重叠

javascript - 如果发生验证错误,Ajax 表单将发送两次

javascript - 使用 Javascript 或 JQuery 插入响应式 CSS 规则

javascript - 如何停止jquery更改单个div上所有div的css

Javascript UI 渲染技术

javascript - 在 mousedown 和 mousemove 事件中获取鼠标位置