javascript - 转到 mouseleave 上最后单击的元素

标签 javascript jquery html css

我想要完成的是:

  1. mouseenter:悬停 5 个框中的 1 个后,部分背景会发生变化,具体取决于悬停这 5 个框中的哪一个。

  2. 点击:点击 5 个框之一后,下方部分的背景会停在相应的图片上,具体取决于点击的框。

  3. mouseleave:在此事件之后,该部分的背景应返回上次单击的背景或如果没有点击则返回默认选择。

这是我做的一支笔,它会更容易理解我想要完成的事情:https://codepen.io/karamanliev/pen/YewOpG

$box = jQuery(".box");
$boxes = jQuery(".boxes");
$section = jQuery(".section-bg");
$default = jQuery(".--3");

jQuery($box).mouseenter(function() {

    $section.eq(jQuery(this).index()).siblings().removeClass("active");
    $section.eq(jQuery(this).index()).addClass("active");

    jQuery($box).click(function() {

        $section.eq(jQuery(this).index()).siblings().removeClass("active");
        $section.eq(jQuery(this).index()).addClass("active");

        jQuery(this).attr('clicked', 'yes'); 
        return true;

    });
}).mouseleave(function() {

    if (jQuery(this).attr('clicked') != 'yes') {
        $section.eq(jQuery(this).index()).removeClass("active");
        $default.addClass("active");

    }

});

问题是在我已经点击一个框并再次悬停后,它会回到默认选择 (--3)。

最佳答案

1st:您需要将clicked="yes"添加到事件框

<div class="box active" clicked="yes">
  <p>3</p>
</div>

第 2 您需要从非事件框中删除 clicked 属性

 jQuery($box).removeAttr('clicked');

3rd 无需使用 $default 或使用 if 语句来检查 上的 clicked 属性>mouseleave().. 足以使用 .filter()

$section.removeClass('active');
$section.eq(jQuery($box).filter('.active[clicked]').index()).addClass("active");

CodePen

关于javascript - 转到 mouseleave 上最后单击的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48593374/

相关文章:

javascript - 无法覆盖 CSS 规则

html - 仅使用 html 和 css 的 html 按钮中的 facebook 样式通知

javascript - 使用 JS 和 NodeJS 上传文件 post 请求

javascript - 浏览器关闭时终止 session

javascript - 选择下拉选项并显示不同的图像(使用 Javascript)

JQuery + SVG 对象 : Capture click event properly

javascript - jQuery 循环遍历 JSON 对象

javascript - React-google-charts,ColumnChart 返回未处理的拒绝错误 : Failed to set DataTable from data props

javascript - 使用按钮在 Jquery Datepicker 上设置日期

css - 为什么 "adContent"类名在 css 中不起作用