jQuery实现操作框的实现和隐藏功能

时间:2022-08-31 16:34:00
问题描述:如下图所示,要实现以下功能。
1、实现点击蓝色操作按钮,左边出现操作框。
2、再点击一次操作按钮,出现的操作框消失。
3、点击其他行的操作按钮,原先的出现操作框消失。
4、点击页面空白处,原先出现的操作框消失。
jQuery实现操作框的实现和隐藏功能

js代码如下:
<script type="text/javascript">
var beforeButton=null;
$(function(){

// 点击空白,操作面板消失
$("body").click(function(){
if(beforeButton!=null){
beforeButton.next().attr("class","false");
beforeButton.css({
"background-color":"white",
"color":"#0098e7",
});
beforeButton=null;
}
});

$("#operationBody").click(function(e){
e.stopPropagation();
});

// 点击操作按钮,在按钮的左边弹出操作框
$(".newsMoreContentMessage #newsMoreBusinessOper #newsMoreBusinessOperBody").click(function(e){


var operationBodyTop=$(this).position().top+6;
var operationBodyLeft=$(this).position().left-75;
$(this).next().css({
"top":operationBodyTop,
"left":operationBodyLeft,
});


if('true'==$(this).next().attr("class")){
$(this).next().attr("class","false");
$(this).css({
"background-color":"white",
"color":"#0098e7",
});
}else{
$(this).next().attr("class","true");
$(this).css({
"background-color":"#0098e7",
"color":"white",
});
}

//判断当前点击的按钮和前一次已点击的按钮是否为同一个
var beforeButtonValue="";
if(beforeButton!=null){
beforeButtonValue=beforeButton.parents("#newsMoreBusinessOper").attr("class");
}
var thisValue=$(this).parents("#newsMoreBusinessOper").attr("class");
if(beforeButton!=null&&beforeButtonValue!=thisValue){

beforeButton.next().attr("class","false");
beforeButton.css({
"background-color":"white",
"color":"#0098e7",
});
beforeButton=null;
}
beforeButton=$(this);
e.stopPropagation();
});


$(window).resize(function(){
$(".newsMoreContentMessage #newsMoreBusinessOper #newsMoreBusinessOperBody").click(function(){
var operationBodyTop=$(this).position().top+6;
var operationBodyLeft=$(this).position().left-75;
$(".newsMoreContentMessage #newsMoreBusinessOper #operationBody").css({
"top":operationBodyTop,
"left":operationBodyLeft,
});

});
});
</script>



jsp代码如下:
<div id="newsMoreBusinessOper" class="<%=index%>">
<div id="newsMoreBusinessOperBody">+操作</div>
<div id="operationBody" class="false">
<div><a href="http://www.baidu.com">详细信息</a></div>
<div><img src="/Jxdoe-BusinessManager-portlet/img/delete.png"></img>删除</div>
</div>
</div>



主要知识点如下:
1、e.stopPropagation()
e.stopPropagation();就是阻止冒泡,冒泡会从最里层,也就是你点击的位置以此向外触发事件,比如点击事件……
在这里添加了e.stopPropagation();之后,除了点击处的事件,它的父元素事件就不会被触发了,因为已经被阻止了。

在jQuery中,其实这句也可也用 return false来替代,但是在JS中不行。

备注:在jQuery中,return false在使用上等于 stopPropagation() 加 preventDefault()

如果在JS中使用stopPropagation()方法阻止事件的传递。

需要html元素以事件event作为参数传到调用方法中,如下代码所示:

<input type="button" value="点击" id="but12" onclick="mb(event)">
function mb(event){
//console.log($(item).attr("valss"));
$("#ul12").toggleClass("change");
event.stopPropagation();
}
或者在JS中,首先获取元素对象,然后设置该对象的事件,此时和上面jQuery的类似。代码如下:
document.getElementById("but12").onclick=function mb(eve){
alert("button方法");
eve.stopPropagation();
}