我希望在单击按钮时从浏览器的左边缘滑动面板,并在单击相同的按钮(切换)时隐藏面板.
HTML
<div class="panel">
</div>
<a href="javascript:void(0);" class="slider-arrow show">»</a>
Run Code Online (Sandbox Code Playgroud)
CSS
.panel {
width:300px;
float:left;
height:550px;
background:#d9dada;
position:relative;
left:-300px;
}
.slider-arrow {
padding:5px;
width:10px;
float:left;
background:#d9dada;
font:400 12px Arial, Helvetica, sans-serif;
color:#000;
text-decoration:none;
position:relative;
left:-300px;
}
Run Code Online (Sandbox Code Playgroud)
jQuery的
$(function(){
$('.slider-arrow.show').click(function(){
$( ".slider-arrow, .panel" ).animate({
left: "+=300"
}, 700, function() {
// Animation complete.
});
$(this).html('«').removeClass('show').addClass('hide');
});
$('.slider-arrow.hide').click(function(){
$( ".slider-arrow, .panel" ).animate({
left: "-=300"
}, 700, function() {
// Animation complete.
});
$(this).html('»').removeClass('hide').addClass('show');
});
});
Run Code Online (Sandbox Code Playgroud)
它显示面板但不隐藏面板.使用选择器有任何问题吗?
Tre*_*vor 12
正如其他人在jQuery中所述,一旦文档被初始化,它只会查找最初存在的元素.因此,您的.show功能每次都在运行.
.slider-arrow.show您可以查看,.slider-arrow然后在单击此类示例后检查类,而不是查找单击事件.
$(function(){
$('.slider-arrow').click(function(){
if($(this).hasClass('show')){
$( ".slider-arrow, .panel" ).animate({
left: "+=300"
}, 700, function() {
// Animation complete.
});
$(this).html('«').removeClass('show').addClass('hide');
}
else {
$( ".slider-arrow, .panel" ).animate({
left: "-=300"
}, 700, function() {
// Animation complete.
});
$(this).html('»').removeClass('hide').addClass('show');
}
});
});
Run Code Online (Sandbox Code Playgroud)
由于您在 DOM 加载后使用 jQuery 来操作“显示”和“隐藏” ,因此 jQuery 不知道这些元素存在。
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call...
我建议使用 jQueryon()来委托事件并选择动态生成的类,如下所示:
$(document).on('click','.slider-arrow.show',function(){
....
});
$(document).on('click','.slider-arrow.hide',function(){
....
});
Run Code Online (Sandbox Code Playgroud)