【发布时间】:2016-02-09 15:00:24
【问题描述】:
我是纯 Javascript 的初学者。我想创建一个效果,例如使用 jquery 创建的效果:
var mouseX = 0, mouseY = 0, limitX, limitY, containerWidth;
$(document).ready(function() {
//Declaring the container size variable when we dom is ready
//Grabbing the size of an element gives a number no longer a percentage
containerWidth = $(".container").width();
containerHeight = $(".container").height();
$("#debug").html('Container Width = ' + containerWidth + '<br/>Container Height = ' + containerHeight);
// cache the selector
var follower = $("#follower");
var xp = 0, yp = 0;
// limitX is now the difference between the #container's width (=80%) and 15px
limitX = containerWidth-15;
limitY = containerHeight-15;
var loop = setInterval(function(){
// change 12 to alter damping higher is slower
xp += (mouseX - xp) / 6;
yp += (mouseY - yp) / 6;
follower.css({left:xp, top:yp});
}, 15);
//Since changing the window size affects the width, we need to redefine the container size variable so that's it's current
$(window).resize(function() {
//this makes limiX change based on container width
limitX = $(".container").width()-15;
$("#debug").html('Container Width = ' + containerWidth + '<br/>Container Height = ' + containerHeight);
}).resize();
$(document).on('mousemove', function (e) {
mouseX = Math.min(e.pageX, limitX);
mouseY = Math.min(e.pageY, limitY);
});
});
链接到用户的小提琴:http://jsfiddle.net/alexchopjian/5QfYL/5/, 但使用纯Javascript。可能吗?
我将非常感谢任何有关如何解决此问题的线索。
【问题讨论】:
-
你好,我的意思是把上面用jquery写的代码变成一个纯javascript的解决方案。
-
这是可能的,因为 jQuery 只是更多的 JavaScript。见罗伯托的评论。我理解对库不太满意的愿望,但考虑到它是一个经过高度测试的库,可以简化浏览器兼容性,并且它使你必须维护的 js 更小,更容易编写和维护,因此使用 jQuery 确实是一个很小的代价。
标签: javascript jquery