用jquery写了视差。
我的javascript技巧很糟糕
你能把我的代码放到vanilla js的路上吗。
https://jsfiddle.net/Islam_Ibakaev/yqb2sbgc/15/#username
$('#intro').on('mousemove', function(e) {
var w = $(window).width();
var offsetX = 0.5 - e.pageX / w;
var moon = $(this).find('.moon');
var buildings = $(this).find('.buildings');
var offsetForM = parseInt(moon.data('offset'));
var offsetForB = parseInt(buildings.data('offset'));
var translateM = "translate(" + Math.round(offsetX * offsetForM) + "px";
var translateB = "translate(-" + Math.round(offsetX * offsetForB) + "px";
moon.css({
'-webkit-transform': translateM,
'transform': translateM,
'moz-transform': translateM
});
buildings.css({
'-webkit-transform': translateB,
'transform': translateB,
'moz-transform': translateB
});
});
答案 0 :(得分:6)
this你需要什么?
document.getElementById('intro').onmousemove = function(e) {
var w = window.innerWidth;
var offsetX = 0.5 - e.pageX / w;
var moon = document.getElementsByClassName('moon')[0];
var buildings = document.getElementsByClassName('buildings')[0];
var offsetForM = parseInt(moon.getAttribute('data-offset'));
var offsetForB = parseInt(buildings.getAttribute('data-offset'));
var translateM = "translate(" + Math.round(offsetX * offsetForM) + "px";
var translateB = "translate(-" + Math.round(offsetX * offsetForB) + "px";
moon.style.webkitTransform = translateM;
moon.style.MozTransform = translateM;
moon.style.transform = translateM;
buildings.style.webkitTransform = translateB;
buildings.style.MozTransform = translateB;
buildings.style.transform = translateB;
};