[英]How can I create a function so that the content in a modal window scrolls to top when body prevents scroll?
I'm quite new to developing and I'm right creating my portfolio. 我对开发很陌生,现在正在创建自己的投资组合。 I have modal window where the user can display and browse between different projects. 我有模式窗口,用户可以在其中显示和浏览不同的项目。 I'm using javascript for browsing the project and I've have set the body to prevent body scroll when scrolling the modal window. 我正在使用javascript浏览项目,并且已经设置了主体以防止在滚动模式窗口时主体滚动。 My problem: How can I create a function so that the content in a modal window scrolls to the top when browsing the next project? 我的问题:浏览下一个项目时,如何创建一个函数,以便模态窗口中的内容滚动到顶部? Right now you end up at the same position as where you left the previous project. 现在,您最终离开的位置与上一个项目所在的位置相同。
//Open modal
function openModal() {
document.getElementById("projectModal").style.display ="block";
noScroll();
}
// Close Modal
function closeModal() {
document.getElementById("projectModal").style.display ="none";
addScroll();
}
var projectIndex =1;
showProjects(projectIndex);
function nextProject(n) {
showProjects(projectIndex+=n);
}
function currentProject(n) {
showProjects(projectIndex=n);
}
function showProjects(n) {
var i;
var projects = document.getElementsByClassName("projects");
if (n>projects.length) {
projectIndex =1
}
if (n<1) {
projectIndex= projects.length
}
for (i=0;i<projects.length; i++) {
projects[i].style.display = "none";
}
projects[projectIndex-1].style.display ="block";
}
// Prevent bodyscrolling
function noScroll() {
body.classList.add("noScroll");
}
//Enables bodyscrolling
function addScroll() {
body.classList.remove("noScroll");
}
Just set the scrollTop
of the element to 0: 只需将元素的scrollTop
设置为0:
function openModal() {
var modal = document.getElementById("projectModal");
modal.scrollTop = 0;
modal.style.display ="block";
noScroll();
}
Solution 解
var modal = document.getElementById("projectModal");
var modalContent = document.getElementById("modalContent");
function openModal() {
modal.style.display ="block";
noScroll();
}
// Close Modal
function closeModal() {
modal.style.display ="none";
addScroll();
}
var projectIndex =1;
showProjects(projectIndex);
function nextProject(n) {
showProjects(projectIndex+=n);
}
function currentProject(n) {
showProjects(projectIndex=n);
}
function showProjects(n) {
var i;
var projects = document.getElementsByClassName("projects");
if (n>projects.length) {
projectIndex =1
}
if (n<1) {
projectIndex= projects.length
}
for (i=0;i<projects.length; i++) {
projects[i].style.display = "none";
}
projects[projectIndex-1].style.display ="block";
modalContent.scrollTop = 0;
}
// Prevent bodyscrolling
function noScroll() {
body.classList.add("noScroll");
}
//Enables bodyscrolling
function addScroll() {
body.classList.remove("noScroll");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.