如何改变鼠标移动的梯度?

时间:2015-01-10 11:26:00

标签: javascript jquery html5 css3 canvas

我受到来自http://codepen.io/andreasstorm/pen/syvoL

的代码sinppet的启发

HTML -

<header>
    <div id="range"></div>
      <div id="currentVal">background-image: linear-gradient( <span id="spanVal">180</span>deg , <span style="color:#4ac1ff">#4ac1ff</span>, <span style="color:#795bb0">#795bb0</span> )</div>
</header>
<div class="gradient"></div>

CSS(手写笔) -

 html
  height 100%

 body
  background-color #292c2f
  font-family monospace
  overflow hidden

 .gradient
  height calc(100% - 70px)
  background-image linear-gradient(180deg,#4ac1ff,#795bb0)
  position absolute
  width 100%

 header
  background #252525
  height 70px
  line-height 70px

 #currentVal
  color #424242
  font-size 14px
  font-weight 800
  padding-left 240px
  span
    color #ccc

 #range
  width 180px
  border 0
  height 4px
  background #424242
  outline none
  position absolute
  left 30px
  top 32px
  .ui-slider-handle
    position absolute
    margin 0px 0 0 -7px
    border-radius 100%
    background white
    border 0
    height 14px
    width 14px
    outline none
    cursor pointer
    &:hover
    &:focus
      transform scale(1.1)
  .ui-slider-range
    background #4ac1ff

JavaScript(coffeeScript) -

$("#range").slider
  range: "min"
  max: 360
  value: 180
  slide: (e, ui) ->
    $("#spanVal").html ui.value
    bg = "linear-gradient(" + ui.value + "deg,#4ac1ff,#795bb0)"
    $(".gradient").css "background-image", bg

我试图在网页的背景上实现它,尽管我并不精通JavaScript。无论如何我们可以对鼠标移动实现相同的效果吗?我的意思是改变渐变的程度以及光标在屏幕上的位置。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

this怎么样?你正在寻找什么?

$(".gradient").mousemove(function( event ) {
  var w = $(this).width(),
      pct = 360*(+event.pageX)/w,
      bg = "linear-gradient(" + pct + "deg,#4ac1ff,#795bb0)";
      $(".gradient").css("background-image", bg);
});

我只使用x动作。你可以使用你喜欢的。用户使用类.gradient将鼠标移动到div旁边。我只是使用div的宽度将值调整为百分比,然后更改背景。

答案 1 :(得分:1)

添加x + y并给出随机度

var originalBG = $(".gradient").css("background");

$('.gradient')
  .mousemove(function(e) {

    x = e.pageX - this.offsetLeft;
    y = e.pageY - this.offsetTop;
    xy = x + y;
    bgWebKit = "linear-gradient(" + xy + "deg, #4ac1ff, #795bb0)";

    $(this).css({
      'background': bgWebKit
    })
  }).mouseleave(function() {
    $(this).css({
      background: originalBG
    });
  });
* {
  margin: 0;
  padding: 0;
}
html {
  height: 100%;
}
body {
  background-color: #292c2f;
  font-family: monospace;
  overflow: hidden;
}
.gradient {
  height: calc(100%);
  background: -webkit-linear-gradient(270deg, #4ac1ff, #795bb0);
  background: -moz-linear-gradient(270deg, #4ac1ff, #795bb0);
  background: -o-linear-gradient(270deg, #4ac1ff, #795bb0);
  background: -ms-linear-gradient(270deg, #4ac1ff, #795bb0);
  background: linear-gradient(180deg, #4ac1ff, #795bb0);
  position: absolute;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="gradient"></div>