[英]Jquery fade divs in and out
我正在嘗試使用jQuery使一組div淡入和淡出。 我有一個解決方案,盡管看起來很笨拙。 有沒有一種方法可以簡化我的代碼? 我是jQuery的新手,因此非常感謝您的幫助!
HTML:
<a class="button" href="javascript:void(0)" id="onelink">Show Div One</a>
<a class="button" href="javascript:void(0)" id="twolink">Show Div Two</a>
<a class="button" href="javascript:void(0)" id="threelink">Show Div Three</a>
<a class="button" href="javascript:void(0)" id="fourlink">Show Div Four</a>
<div class="content">
<div id="one" class="thing">One</div>
<div id="two" class="thing">Two</div>
<div id="three" class="thing">Three</div>
<div id="four" class="thing">Four</div>
</div>
SCSS:
a.button {
text-decoration: none;
color: #000;
display: inline-block;
padding: 10px;
margin: 20px;
border: 1px solid #000;
@include transition (all 0.2s);
&:hover {
border: 1px solid #dadada;
background-color: #f5f5f5;
}
}
div.thing {
border: 1px solid #BADA55;
background-color: #dadada;
padding: 30px;
text-align: center;
width: 200px;
margin: 20px;
position: absolute;
display: none;
&#one {
display: block;
}
}
JQUERY:
$(document).ready(function() {
$("#onelink").click(function() {
$("div#one").fadeIn();
$("div#two, div#three, div#four").fadeOut();
});
$("#twolink").click(function() {
$("div#two").fadeIn();
$("div#one, div#three, div#four").fadeOut();
});
$("#threelink").click(function() {
$("div#three").fadeIn();
$("div#one, div#two, div#four").fadeOut();
});
$("#fourlink").click(function() {
$("div#four").fadeIn();
$("div#one, div#two, div#three").fadeOut();
});
});
Codepen鏈接在這里:
使用data-attributes
,因此假設#onelink
打開div#one
#onelink
添加data-id = "one"
,依此類推。
<a class="button" href="" data-id="one">Show Div One</a>
<a class="button" href="" data-id="two">Show Div Two</a>
<a class="button" href="" data-id="three">Show Div Three</a>
<a class="button" href="" data-id="four">Show Div Four</a>
編輯:
可以刪除javascript:void(..)
並使用event.preventDefault()
處理默認事件<a>
。
或者也許只是刪除href
並在CSS中處理cursor
。
而且,正如@Regent所建議的那樣,由於該解決方案適用於類,因此不再需要ID id="onelink"
..。
$(document).ready(function() {
$(".button").click(function(event) {
event.preventDefault();
var $divtoRender = $("#"+$(this).data('id'));
$divtoRender.fadeIn();
$("div.thing:visible").not($divtoRender).fadeOut();
});
});
而不是添加單獨的處理程序為每個按鈕,你可以使用通用的處理程序,並使用href
來指定哪些thing
來顯示。
<a class="button" href="#one">Show Div One</a>
<a class="button" href="#two">Show Div Two</a>
<a class="button" href="#three">Show Div Three</a>
<a class="button" href="#four">Show Div Four</a>
<div class="content">
<div id="one" class="thing">One</div>
<div id="two" class="thing">Two</div>
<div id="three" class="thing">Three</div>
<div id="four" class="thing">Four</div>
</div>
然后
$(document).ready(function () {
var $things = $('.thing');
$(".button").click(function (e) {
e.preventDefault();
var $div = $($(this).attr('href'));
$div.stop().fadeIn();
$things.not($div).stop().fadeOut();
});
});
演示: 小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.