简体   繁体   English

随着鼠标越来越近,如何增加元素大小?

[英]How to increase element size as mouse gets closer?

I was just messing around in jsfiddle trying to resize a box base on the mouse position. 我只是在jsfiddle中乱搞,试图调整鼠标位置的盒子大小。 Making the box larger as the mouse moves away is simple, just get the distance. 当鼠标移开时使盒子变大是很简单的,只需要距离。 However, I want to do the opposite; 但是,我想做相反的事情; I want the box to increase in size as the mouse gets closer and decrease as the mouse moves away. 随着鼠标移动越来越近,我希望盒子的尺寸增大,随着鼠标的移动而减小。 I haven't been able to think up any formulas for this. 我还没有想出任何公式。 I feel there could be something really simple that I am missing. 我觉得我可能会有一些非常简单的事情。

<div id="box"></div>

#box { height: 100px; width: 100px; background: black; }

var box = document.getElementById('box');

// center point of the box
var boxX = 50;
var boxY = 50;

document.addEventListener('mousemove', function(e) {
    var x = e.pageX,
        y = e.pageY;

    var dx = x - boxX,
        dy = y - boxY;

    var distance = Math.sqrt(dx *dx + dy * dy);

    box.style.width = box.style.height = distance + 'px';

}, false);

Here is a link to the fiddle: http://jsfiddle.net/gSDPq/ 这是一个小提琴的链接: http//jsfiddle.net/gSDPq/

Any help is appreciated, Thanks 任何帮助表示赞赏,谢谢

Try distance = Math.max(0,200-Math.sqrt(dx*dx + dy*dy)); 尝试distance = Math.max(0,200-Math.sqrt(dx*dx + dy*dy));

This should have the box disappear when the mouse is 200px or more away, and steadily grow to 200px in size as you get nearer the middle. 当鼠标距离200px或更远时,这应该让盒子消失,当你接近中间时,它会逐渐增大到200px。 Adjust numbers as needed (for instance, divide the Math.sqrt() part by 2 to reduce the effect that distance has, or adjust the 200 to affect the max size) 根据需要调整数字(例如,将Math.sqrt()部分除以2以减少距离的影响,或调整200以影响最大尺寸)

jsfiddle 的jsfiddle

var box = document.getElementById('box');  
// center point of the box
var boxX = 50;
var boxY = 50;
var ux=500, uy=500;// 1.stage
document.addEventListener('mousemove', function(e) {
    var x = e.pageX,
        y = e.pageY;

    var dx = ux-(x - boxX),
        dy = uy-(y - boxY);// 2.stage

    var distance = Math.sqrt(dx *dx + dy * dy);

    box.style.width = box.style.height = distance + 'px';

}, false);

I'm not sure that Kolink's answer actually did what you wanted to do. 我不确定Kolink的答案是否真的做了你想做的事。 You seem to want the box to grow when the mouse is getting closer to it. 当鼠标越来越近时,你似乎希望盒子能够生长。

Just subtracting both x and boxX from some predefined box size value should do that: 只需从某个预定义的框大小值中减去xboxX即可:

var dx = 400 - x - boxX,
    dy = 400 - y - boxY;
if(dx<0) dx = 0;
if(dy<0) dy = 0;

http://jsfiddle.net/gSDPq/3/ http://jsfiddle.net/gSDPq/3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM