Javascript 如何将jQuery css样式更改为vanilla JS
我在jQuery中得到了一个代码,我需要将其转换为纯javascript代码Javascript 如何将jQuery css样式更改为vanilla JS,javascript,jquery,Javascript,Jquery,我在jQuery中得到了一个代码,我需要将其转换为纯javascript代码 $(window).scroll(function () { $('.baner').css({'transform':'translate3d(0px, '+(-($(this).scrollTop()/5))+"px"+', 0px'}); }); 我想做的是: 让win=document.querySelectorwindow; 让banner=document.getElemen
$(window).scroll(function () {
$('.baner').css({'transform':'translate3d(0px, '+(-($(this).scrollTop()/5))+"px"+', 0px'});
});
我想做的是:
让win=document.querySelectorwindow;
让banner=document.getElementById'baner';
win.addEventListener'scroll'函数{
css{'transform':'translate3d0px',+-$this.scrollTop/5+px+',0px'};
};
确保这是正确的:
let banner = document.getElementById('banner');
你不用了,因为你已经说过这是一个Id
正如Kalinuskas在回答中提到的,您可以使用document.getElementById
// () => {} is ES6 shorthand for a function (also called arrow function, read about it here https://www.w3schools.com/js/js_arrow_function.asp
// Instead of the .css function for jQuery, you have .style.yourStyleAtributeHere
let banner = document.getElementById('baner');
window.addEventListener("scroll", () => {
banner.style.transform = 'translate3d(0px, ' + (-(banner.scrollTop / 5))+"px"+', 0px'
});
这很好,但这不是question.banner.style中代码的唯一问题,它允许您访问banner元素的样式属性。正如@kalinuskas所说的,要么使用getElementbyId'banner',要么使用querySelector'banner',元素id中可能的拼写错误得到纠正。
// () => {} is ES6 shorthand for a function (also called arrow function, read about it here https://www.w3schools.com/js/js_arrow_function.asp
// Instead of the .css function for jQuery, you have .style.yourStyleAtributeHere
let banner = document.getElementById('baner');
window.addEventListener("scroll", () => {
banner.style.transform = 'translate3d(0px, ' + (-(banner.scrollTop / 5))+"px"+', 0px'
});