0

我正在使用 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/

非常感谢你的帮助

4

2 回答 2

0

你最好使用 mouseleave 而不是 mouseout

$('a').mouseleave(function(e){
    $('a').css({'color':'#000', 'border':'none'});
});
于 2014-02-07T14:19:44.473 回答
0

由于小提琴中的一些重大变化,我将在这里回答,而不是将其作为评论。如果我理解正确,您希望链接的颜色根据您在其上移动的位置而改变,并让链接在您单击它(或激活它)时保持该颜色。

在这个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 + ")");
});

编辑:更新以更改移动鼠标上活动链接的颜色。

于 2014-02-07T15:32:52.213 回答