无法设置切换按钮效果

时间:2014-01-25 05:30:43

标签: jquery html css

我在这里有点困境。 我想要做的是我试图制作2个并排按钮,当一个人徘徊时,它会改变背景颜色,当另一个徘徊时,它会发生变化。像一个切换。 现在问题出现了,我想要点击一个它保留效果就像添加一个类但现在发生的事情是,当我mouseleave它不保留它的状态。 请告诉我我做错了什么。 这里

这是小提琴Fiddle

有些代码就像这样

  $('#masterContainer #leftDiv').mouseenter(function (event) {
            $(this).css('background-color', 'black');
            $(this).css('color', 'white');
            $('#masterContainer #leftDiv img').attr('src', 'heartWhite.png');
        });

2 个答案:

答案 0 :(得分:1)

如果您将所有样式委托给CSS类,那么您可以简化您的问题,这样您所要做的就是更改hoverclick上的框的类。

例如,假设标记:

<div class="box">container one</div>

<div class="box">container two</div>

和CSS:

.box {
    display: inline-block;
    height: 200px;
    width: 400px;
    background: #cdcdcd;
}
.box.hovered, .box.clicked {
    background: #797979;
}

你可以通过以下方式实现听起来的效果:

// Handle the mouseenter/leave events with a unique class
$('.box').on('mouseenter', function() {
    $(this).addClass('hovered');
}).on('mouseleave', function() {
    $(this).removeClass('hovered');
});
// Handle click event with a different class and toggle method
$('.box').on('click', function() {
    $(this).toggleClass('clicked');
});

或者,如果您希望根据点击切换的框,您可以使用:

$('.box').on('click', function() {
    $(this).removeClass('hovered');
    $(this).siblings('.box').addClass('hovered')
});
// Use this block instead of the previous `click` handler above

将样式抽象到样式表(而不是使用.css方法)的优点是:

一个。它将您的外观与标记分开(关注点分离),并避免使用内联样式覆盖问题。

B中。它通过将问题减少到类添加/删除来显着简化您的DOM交互。

这是Fiddle

答案 1 :(得分:0)

有太多的javascript去那么简单的事情了。 (如果我理解你在寻找什么。)

小提琴:http://jsfiddle.net/xYLyT/2/

让CSS完成工作。 :)

HTML:

<div class="container">
    <div class="box zuck">
        Zuck
    </div>
    <div class="box albert">
        Albert
    </div>
</div>

JS:

$('.box').click(function (event) {
    $('.box').removeClass('clicked');
    $(this).addClass('clicked');
    event.stopPropagation();
});

CSS:

body {
  background-color : silver;
  margin           : 0;
  padding          : 0;
}
* {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  }

.container {
  border : 2px solid black;
  float  : left;
  height : 180px;
  width  : 803px;
}

.box {
  border-right : 1px solid black;
  float        : left;
  height       : 100%;
  transition   : all 1s ease 0s;
  width        : 50%;
  padding: 0;
}
.box:hover,
.box.clicked {
    background-color: black;
    color: white;
}
.zuck {
  background: url('https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTUZnc_P0eH1w67I_YaaWo18Tgt83RFrepGDJm-AA8d9pg_kWM8Pw') no-repeat center center;

}

.albert {
  background: url('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRYtxk2DUEWNsNpH0jTMqLc22tYccLZiwYxiCKKOCLGTVr2QZp_nw') no-repeat center center;
}