简体   繁体   English

使用JavaScript在页面加载上缩放div

[英]Zoom div on page load using Javascript

I'm using the following code to show a div when it is scrolled into view. 当滚动到视图中时,我使用以下代码显示div。 I would like to simplify this and show the div when the page loads and not when scrolled into view. 我想简化此过程,并在页面加载时显示div,而不是在滚动到视图时显示div。 Any help would be great. 任何帮助都会很棒。 Many thanks. 非常感谢。

 var animateHTML = function () { var elems, windowHeight var init = function () { elems = document.getElementsByClassName('hidden') windowHeight = window.innerHeight _addEventHandlers() } var _addEventHandlers = function () { window.addEventListener('scroll', _checkPosition) window.addEventListener('resize', init) } var _checkPosition = function () { for (var i = 0; i < elems.length; i++) { var posFromTop = elems[i].getBoundingClientRect().top if (posFromTop - windowHeight <= 0) { elems[i].className = elems[i].className.replace('hidden', 'fade-in-element') } } } return { init: init } } animateHTML().init() 

You can use Element#scrollIntoView to make the element visible in the viewport. 您可以使用Element#scrollIntoView使该元素在视口中可见。

You can use the DOMContentLoaded event to know when the DOM is ready. 您可以使用DOMContentLoaded事件来了解DOM准备就绪的时间。

Note : the options object - { behavior: 'smooth', block: 'center' } is only supported by Chrome and Firefox. 注意 :仅Chrome和Firefox支持options对象- { behavior: 'smooth', block: 'center' } Other browsers support only a the alignToTop boolean, and since the object will evaluate to true the element will jump to the top. 其他浏览器仅支持alignToTop布尔值,并且由于该对象的值为true该元素将跳到顶部。

 document.addEventListener("DOMContentLoaded", function(event) { document.querySelector('.active').scrollIntoView({ behavior: 'smooth', block: 'center' }); }); 
 .block { width: 100px; height: 100px; border: 1px solid red; } .active { border: 1px solid blue; } 
 <div class="block"></div> <div class="block"></div> <div class="block"></div> <div class="block"></div> <div class="block"></div> <div class="block"></div> <div class="block"></div> <div class="block"></div> <div class="block"></div> <div class="block active">Scroll into view</div> <div class="block"></div> <div class="block"></div> 

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

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