[英]links hover and active color change depending on mouse position with Javascript
我正在使用JS脚本根据鼠标位置更改div背景颜色。
$(document).mousemove(function(e){
var $width = ($(document).width())/(252 - 23);
var $height = ($(document).height())/(253 - 2);
var $pageX = 253 - parseInt(e.pageX / $width,10);
var $pageY = 200 - parseInt(e.pageY / $height,10) + 2;
$("body").css("background-color", "rgb("+$pageY+","+$pageY+","+$pageY+")");
});
它工作得很好。
我现在想做的是,当鼠标悬停和活动时,将相同的颜色更改应用于链接。
尝试此代码时,颜色会根据鼠标的位置在悬停时发生变化,但是当鼠标移出时,更改的颜色属于:
$(document).mousemove(function(e){
var $width = ($(document).width())/(252 - 23);
var $height = ($(document).height())/(253 - 2);
var $pageX = 253 - parseInt(e.pageX / $width,10);
var $pageY = 200 - parseInt(e.pageY / $height,10) + 2;
$("a:hover").css("color", "rgb("+$pageX+","+$pageY+","+$pageX+")");
$("a:hover").css("border-bottom", "1px dotted rgb("+$pageX+","+$pageY+","+$pageX+")");
$("a:active").css("color", "rgb("+$pageX+","+$pageY+","+$pageX+")");
$("a:active").css("border-bottom", "1px dotted rgb("+$pageX+","+$pageY+","+$pageX+")");
});
我想我需要添加一个mouseover和mouseout函数,但是我不知道该怎么做...
有人知道我该怎么做吗?
这是一个jsfiddle: http : //jsfiddle.net/BrZjJ/36/
非常感谢你的帮助
您最好使用mouseleave而不是mouseout
$('a').mouseleave(function(e){
$('a').css({'color':'#000', 'border':'none'});
});
由于小提琴中发生了一些重大变化,因此我将在此处回答而不是将其保留为注释。 如果我没看错,您希望链接的颜色根据您在链接上的移动位置而改变,并让链接在单击(或激活)时保持该颜色。
在这个jsFiddle中,它只是这样做的:
的CSS
a.active {
border-bottom: 1px dotted;
}
a:visted {
color:blue;
}
a {
color: blue;
text-decoration: none;
}
a:hover {
border-bottom: 1px dotted;
}
的JavaScript
var pageX, pageY;
$(document).mousemove(function (e) {
var $width = ($(document).width()) / (252 - 23);
var $height = ($(document).height()) / (253 - 2);
var $pageX = 253 - parseInt(e.pageX / $width, 10);
var $pageY = 200 - parseInt(e.pageY / $height, 10) + 2;
$("body").css("background-color", "rgb(" + $pageY + "," + $pageY + "," + $pageY + ")");
});
$(document).mousemove(function (e) {
var $width = ($(document).width()) / (252 - 23);
var $height = ($(document).height()) / (253 - 2);
pageX = 253 - parseInt(e.pageX / $width, 10);
pageY = 200 - parseInt(e.pageY / $height, 10) + 2;
$("a").on("mousemove", function () {
$(this).css("color", "rgb(" + pageX + "," + pageY + "," + pageX + ")");
}).on("mouseleave", function () {
if (!$(this).hasClass("active")) $(this).removeAttr("style");
});
$("a.active").css("color", "rgb(" + pageX + "," + pageY + "," + pageX + ")");
});
$("a").on("click", function () {
$("a").removeAttr("style").removeClass("active");
$(this).addClass("active").css("color", "rgb(" + pageX + "," + pageY + "," + pageX + ")");
});
编辑:更新以更改移动鼠标上活动链接的颜色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.