我试图根据鼠标位置改变元素的不透明度。我在这里找到了这个解决方案 - Changing Opacity with Mouse Position - 但我需要一个修改。我正在寻找元素的垂直和水平中心中的不透明度为0。离中心越远,不透明度就越大。
这是我的开发页面:http://www.bjornfloki.com/dev/spoon
我正在使用以下脚本:
var $win = $(window),
w = 0,h = 0,
opacity = 1,
getWidth = function() {
w = $win.width();
h = $win.height();
};
$win.mousemove(function(e) {
getWidth();
opacity = (e.pageX/w * 0.5) + (e.pageY/h * 0.5);
$('#myElement').css('opacity',opacity);
});
答案 0 :(得分:1)
<强>脚本强>
$(function () {
$(document).on("mousemove", function (e) {
var me = $("#scene"),
cx = me.offset().left + me.width() / 2,
cy = me.offset().top + me.height() / 2,
d = (Math.sqrt(Math.pow(cx, 2) + Math.pow(cy, 2))),
md = (Math.sqrt(Math.pow(e.pageX - cx, 2) + Math.pow(e.pageY - cy, 2)));
me.css('opacity', md / d);
-webkit-transition:all 0.5s ease-out;
});
});
<强> HTML 强>
<ul id="scene" class="scene" style="position: relative;">
<li class="layer beresponsive" data-depth="0" style="position: relative; display: block; left: 0px; top: 0px; transform: translate(0px, 0px);">
<img src="http://www.bjornfloki.com/wp-content/themes/wordpress-bootstrap-master-child/images/bg-eyes.jpg" />
</li>
<li class="layer" data-depth="00" style="position: absolute; display: block; left: 0px; top: 0px; transform: translate(0px, 0px);">
<img id="gradient" src="http://www.bjornfloki.com/wp-content/themes/wordpress-bootstrap-master-child/images/empty.png" style="opacity: 0.196366554362154;" />
</li>
<li class="layer" data-depth="00" style="position: absolute; display: block; left: 0px; top: 0px; transform: translate(0px, 0px);">
<img src="http://www.bjornfloki.com/wp-content/themes/wordpress-bootstrap-master-child/images/spoon-logo-1920.png" />
</li>
</ul>
答案 1 :(得分:0)
将centerX设置为水平中心的位置,然后将centerY设置为垂直中心。 通过将currentX和currentY位置的模数组合到centerX和centerY来计算不透明度。
像opacity = [1-(centerX%currentX)] + [1-(centerY%currentY)]
答案 2 :(得分:0)
我认为这有助于你
var window_xy_addition = $(window).height() + $(window).width();
var mouse_position_xy_addition = event.pageY + event.pageX;
$("#change_opacity").css("opacity", (mouse_position_xy_addition/window_xy_addition));