如何将jQuery的.text()、.height()、.css()方法转换为原生JavaScript
原生JavaScript转换方案
完整实现代码
function progress() { // 滚动距离获取,兼容低版本IE const windowScrollTop = window.pageYOffset || document.documentElement.scrollTop; // 文档总高度 const docHeight = document.documentElement.scrollHeight; // 视窗高度 const windowHeight = window.innerHeight; const progress = (windowScrollTop / (docHeight - windowHeight)) * 100; const bgColor = progress > 99 ? "#fff" : "#fff"; const textColor = progress > 99 ? "#fff" : "#333"; // 操作h1元素 const h1 = document.querySelector("h1"); h1.textContent = `${Math.round(progress)}%`; h1.style.color = textColor; // 操作.fill元素 const fill = document.querySelector(".fill"); fill.style.height = `${progress}%`; fill.style.backgroundColor = bgColor; } progress();
多元素兼容写法
如果页面存在多个匹配的h1或.fill元素,需要和原jQuery逻辑一致修改所有匹配元素,可将对应操作部分替换为遍历写法:
// 批量处理所有h1元素 document.querySelectorAll("h1").forEach(el => { el.textContent = `${Math.round(progress)}%`; el.style.color = textColor; }); // 批量处理所有.fill元素 document.querySelectorAll(".fill").forEach(el => { el.style.height = `${progress}%`; el.style.backgroundColor = bgColor; });
核心API对应说明
$(window).scrollTop()→window.pageYOffset || document.documentElement.scrollTop$(document).height()→document.documentElement.scrollHeight$(window).height()→window.innerHeight$('选择器').text(内容)→元素.textContent = 内容$('选择器').css(属性对象)→ 直接给元素.style.属性名赋值即可
内容的提问来源于stack exchange,提问作者jricc russel
相关产品推荐
相关产品推荐

