鼠标移入两标签及离开两标签样式改变
现在打算在我的博客加一个功能,就是复制pre标签内的源代码(当然了,如果有其他可能用到的操作也会加入)。一开始打算是直接通过js插入复制按钮在pre标签内,但这样做的话进行复制操作时从pre获取源代码就包括了这个复制按钮(copyCode)……
所以抛开了这样的做法,干脆在文章内部标签插入复制按钮,默认隐藏,然后鼠标移入pre标签时,定位按钮的位置(主要是top),显示……问题来了,但我移到pre标签上,然后移到复制按钮上,复制隐藏了,再显示……疯狂切换……好吧,复制按钮不在pre标签内,移入复制按钮也就是离开了pre按钮,那么我在进入、离开事件内再加入复制按钮总行了吧……但移入复制按钮时还是闪烁了,而在谷歌浏览器测试时,鼠标在复制按钮处移动时就是疯狂闪烁,定住时没问题……所以离开事件就是离开这两任意标签都会执行……
既然离开事件无法捕获到同时离开两个标签,那么我获取离开时移动的标签总行了吧……这个总算没问题了!
思路:
移入pre显示复制按钮,离开pre标签,mouseout事件判断当前标签 通过事件event.relatedTarget获取当前标签,如果当前标签不是复制按钮,那么隐藏起来
实现:
var tool=" "; var biao1=""; if($(".blogitem article pre").get(0)){ //是否存在pre标签 $(".blogitem article").append(tool,biao1); //显示 隐藏 $(".blogitem article pre").mouseover(function () { var index=$(this).index('pre'); var _top=this.offsetTop+15; $(".blogitem article .tool").css({ top:_top, display:'block' }).data('index',index); }).mouseout(function (e) { if(!$(e.relatedTarget).hasClass('tool') && !$(e.relatedTarget).parent().hasClass('tool') ){ $(".blogitem article .tool").hide(); } }); /*全屏操作*/ $(".Fullscreen").click(function () { var h=window.innerHeight-60 ;//去掉padding、margin if($(this).data("full")){ $($(".blogitem article pre").eq($(this).parent().data('index'))).css({ 'width':'auto', 'position': 'relative', 'z-index':'', 'height':'150px', 'backgroundColor':'transparent' }); $('body').height(''); $(this).data("full",0); }else{ $($(".blogitem article pre").eq($(this).parent().data('index'))).css({ 'width':'98%', 'height':h, 'position': 'fixed', 'left': '0', 'top':0, 'z-index':'99', 'backgroundColor':'#f4ede5' }); $('body').height(h); $(this).data("full",1); } }); //复制操作 $('.blogitem article .copyCode').click(function () { Url2=$($(".blogitem article pre").eq($(this).parent().data('index'))).html(); $('#biao1').val(Url2); $('#biao1').get(0).select(); document.execCommand("Copy"); // 执行浏览器复制命令 alert('复制成功'); }) }