jQuery - 在按钮外部时保持对按钮的关注

时间:2015-11-22 10:24:16

标签: javascript jquery html css

所以我已经能够创建2个按钮。这里:http://jsfiddle.net/0y940r11/2/

在点击按钮外的某个地方后,我真的无法弄清楚如何将注意力集中在点击的按钮上。

有人能指出我的方向吗?



$(document).ready(function() {
  $(".button-off").on("click", function() {
    $(".corner-off").show();
    $(".corner-on").hide();
  });
  $(".button-on").on("click", function() {
    $(".corner-on").show();
    $(".corner-off").hide();
  });
});

.button-on,
.button-off {
  border: 1px solid #ccc;
  height: 120px;
  width: 160px;
  position: relative;
  background: white;
  border-radius: 8%;
}
.button-on:active,
.button-on:focus,
.button-off:active,
.button-off:focus {
  border: 4px solid #FFCC00;
}
.active {
  border: 4px solid #FFCC00;
}
button:active,
button:focus {
  outline: 0;
}
.corner-off,
.corner-on {
  width: 0px;
  height: 0px;
  border-bottom: 30px solid transparent;
  border-left: 30px solid #FFCC00;
  position: absolute;
  top: 0;
  left: 0;
}
.tick:after {
  content: "\2713";
  position: absolute;
  top: -1px;
  left: 5px;
  color: white;
}

<button class="button-on">
  <div class="corner-on" style="display:none"></div>
  <span class="tick"></span>
  ON
</button>

<button class="button-off">
  <span class="corner-off" style="display:none"></span>
  <span class="tick"></span>
  OFF
</button>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

使用$(document).on("click"focus()来实现此目标

&#13;
&#13;
var lastClickedButton = $(".button-on")[0];
$(document).ready(function () {
    $(".button-off").on("click", function () {
        lastClickedButton = this;
        $(".corner-off").show();
        $(".corner-on").hide();
    });
    $(".button-on").on("click", function () {
        lastClickedButton = this;
        $(".corner-on").show();
        $(".corner-off").hide();
    });
});

$(document).on("click", function (e) {$(lastClickedButton).focus();});
&#13;
    .button-on, .button-off {
    border: 1px solid #ccc;
    height: 120px;
    width: 160px;
    position: relative;
    background: white;
    border-radius: 8%;
}
.button-on:active, .button-on:focus, .button-off:active, .button-off:focus {
    border: 4px solid #FFCC00;
}
.active {
    border: 4px solid #FFCC00;
}
button:active, button:focus {
    outline:0;
}
.corner-off, .corner-on {
    width: 0px;
    height: 0px;
    border-bottom: 30px solid transparent;
    border-left: 30px solid #FFCC00;
    position: absolute;
    top: 0;
    left: 0;
}
.tick:after {
    content:"\2713";
    position: absolute;
    top: -1px;
    left: 5px;
    color: white;
}
&#13;
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button-on">
    <div class="corner-on" style="display:none"></div> <span class="tick"></span>
ON</button>
<button class="button-off"> <span class="corner-off" style="display:none"></span>
 <span class="tick"></span>
OFF</button>
&#13;
&#13;
&#13;

演示:http://jsfiddle.net/kishoresahas/0y940r11/4/