元素的特定区域上的背景颜色

时间:2015-10-27 04:19:00

标签: javascript jquery html css

我想要实现的是将悬停效果放在光标的位置上。

类似这样的事:http://drmportal.com/

这是一个小提琴:http://jsfiddle.net/onnmwyhd/

这是我的代码。

HTML

<div id="container"></div>

CSS

#container{
background-color: #6fc39a;
height:200px;
}

JQUERY

$("#container").mousemove(function(e){

var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
    $(this).html("X: " + x + " Y: " + y); 
});

这是我想要的光标位置的颜色....

    background-image: -webkit-linear-gradient(-35deg, #35a28e, #a8e4a5);

2 个答案:

答案 0 :(得分:2)

在您的参考网站中,它使用了画布,请查看这个小提琴,以获得精确的重播

js fiddle

HTML

<div id="container" class="stalker">
    <canvas id="canvas" width="1600" height="433"></canvas>
</div>

CSS

.stalker {
    background-color: #6fc39a;
    height:200px;
    border-top-color: rgba(168, 228, 165, 0.7);
    border-bottom-color: rgba(53, 162, 142, 0.3);
}

脚本

var stalker = $('.stalker');

var canvas = $('#canvas')[0];

var ctx = canvas.getContext('2d'), gradient, initialized = false;

$("#container").mousemove(function(e){
    setTimeout(function(){
        initialized = true;
        canvas.width  = stalker.width();
        canvas.height = stalker.height();
        gradient = ctx.createRadialGradient(e.pageX, e.pageY, 0, e.pageX, e.pageY, canvas.width);
        gradient.addColorStop(0, stalker.css('border-top-color'));
        gradient.addColorStop(1, stalker.css('border-bottom-color'));
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, canvas.width, canvas.height);

    }, initialized ? 200 : 0);
});

答案 1 :(得分:1)

尝试将span元素添加到#container以保存游标值,以避免覆盖元素的html;将div元素添加到#containercss position设置为absoluteleft设置为xtop设置为y以用于使用div

跟踪光标

$(function() {
  $("#container").mousemove(function(e) {
    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
    $("div", this).css({
      left: x - (75 / 2),
      top: y - (75 / 2)
    })
    $("span", this).html("X: " + x + " Y: " + y);
  }).mousemove();
})
#container {
  background-image: -webkit-linear-gradient(-35deg, #35a28e, #a8e4a5);
  background-image: linear-gradient(125deg, #35a28e, #a8e4a5);
  background-color: #6fc39a;
  height: 200px;
}
#container div {
  background-image: -webkit-linear-gradient(-35deg, #35a28e, #a8e4a5);
  width: 75px;
  height: 75px;
  position: absolute;
  border-radius: 100px;
  opacity: 0.5
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

<div id="container">
  <span></span>
  <div></div>

</div>

jsfiddle http://jsfiddle.net/onnmwyhd/2/