我知道有一种简单的方法可以实现这一目标,只是努力让我的头脑。所以我有一个父div包含多个div,如果单击父div之外的div,则需要一个属于它们的open类。请尝试通过html示例解释。
HTML
<div id="mediaPlayer">
<div class="playerViewer">
<div class="playerViewControls">
<img src="img/player-button-prev.png" class="playerPrev" alt="prev" />
<img src="img/player-button-next.png" class="playerNext" alt="next" />
</div>
<div class="playerAll playerView">
<img src="img/placeholder/player-image.jpg" alt="placeholder image" />
</div>
<div class="playerPhoto playerView">
<img src="img/placeholder/player-image.jpg" alt="placeholder image" />
</div>
<div class="playerVideo playerView">
<img src="img/placeholder/player-image.jpg" alt="placeholder image" />
</div>
<div class="playerMap playerView">
<img src="img/placeholder/player-image.jpg" alt="placeholder image" />
</div>
<div class="playerRelated playerView">
<img src="img/placeholder/player-image.jpg" alt="placeholder image" />
</div>
</div>
<div class="playerControl">
<div class="playerBtn playerAll">
<img src="img/player-button-all.jpg" alt="player button all" />
<p>(120) ALL<br />MEDIA</p>
</div>
<div class="playerBtn playerPhoto">
<img src="img/player-button-photo.jpg" alt="player button photo" />
<p>(40) PLACE<br />PHOTOS</p>
</div>
<div class="playerBtn playerVideo">
<img src="img/player-button-video.jpg" alt="player button video" />
<p>(40) PLACE<br />VIDEOS</p>
</div>
<div class="playerBtn playerMap">
<img src="img/player-button-map.jpg" alt="player button map" />
<p>LOCATION<br />MAP</p>
</div>
<div class="playerBtn playerRelated">
<img src="img/player-button-related.jpg" alt="player button related" />
<p>(40) RELATED<br />MEDIA</p>
</div>
</div>
</div>
所以,如果单击.playerBtn.playerAll,我想要这个div和它在.playerViewer(在这种情况下是.playerAll.playerView)里面的对应div来接收开放的类和任何其他div&#39 ;#在#mediaPlayer中打开类,打开类。
答案 0 :(得分:1)
这是一个可能有效的jQuery函数。复杂DOM横向的原因是考虑到单个页面上可能有多个玩家的事件。
$(function() {
$('.playerControl .playerBtn').click(function() {
var $playerViewer = $(this).parent('.playerControl').prev('.playerViewer'),
// Remove the first class called playerBtn
$relatedEle = $playerViewer.find('.'+$(this).attr('class').replace(/playerBtn\s/gi,''));
// Add class
$(this).add($relatedEle).addClass('open');
// Remove class from siblings in two separate containers
$(this).siblings().removeClass('open');
$relatedEle.siblings().removeClass('open');
});
});
请参阅此处的概念验证小提琴:http://jsfiddle.net/kYqcn/
答案 1 :(得分:0)
这样就可以了解
$(".playerBtn.playerAll").on("click", function() {
$(".playerViewer").each(function() {
if($(this).hasClass("open")) {
$(this).removeClass("open");
} else {
$(this).addClass("open");
}
});
});
如果你有不同的父div中的playerViewer div,而不是#mediaPlayer,
将$(".playerViewer")
更改为$("#mediaPlayer .playerViewer")
答案 2 :(得分:0)
试试这个:
$('#mediaPlayer .playerBtn').click(function () {
var className = $.trim($(this).attr('class').replace('playerBtn', ''));
$('#mediaPlayer .open').removeClass('open');
$('#mediaPlayer .' + className).addClass('open');
});