自动居中水平滚动条

我发现了一些相关案例,但没有答案适合我。我的页面有一个很大的水平图像,但我需要从中间开始滚动(只是水平),始终以任何分辨率滚动。


var body = document.body; // For Safari

var html = document.documentElement; // Chrome, Firefox, IE and Opera 

body.scrollLeft = (html.clientWidth - body.scrollWidth) / 2

html.scrollLeft = (html.clientWidth - body.scrollWidth) / 2

body {

  background-color: 0178fa;

  padding: 0;

  text-align: center;

  display: flex;

  justify-content: center;

  align-items: center;

  overflow: auto;

}


#page {

  width: 100%;

  height: 100%;

  margin: 0 auto;

  padding: 0;

  display: block;

}


#wrap-landing {

  position: relative;

  margin: 0 auto;

  padding: 0;

  content: url(https://i.imgur.com/gb6EyHk.png);

  width: 1920px;

  height: 1080px;

}

<div id="page">

  <div id="wrap-landing"></div>

</div>


四季花海
浏览 129回答 2
2回答

犯罪嫌疑人X

您可以使用标准的 javascript:window.scroll(x, y)。前任:window.addEventListener('load', function() {&nbsp; setTimeout(function() {&nbsp; &nbsp; window.scroll(x, y);&nbsp; },1)})x-coord是要在左上角显示的沿文档水平轴的像素。y-coord是要在左上角显示的沿文档垂直轴的像素。window.addEventListener('load', function() {&nbsp; setTimeout(function() {&nbsp; &nbsp; window.scroll(screen.width/2, 0);&nbsp; },1)})body{&nbsp; &nbsp; background-color:0178fa;&nbsp; padding:0;&nbsp; text-align:center;&nbsp; &nbsp; display: flex;&nbsp; justify-content: center;&nbsp; align-items: center;&nbsp; &nbsp; overflow:auto;}#page {&nbsp; &nbsp; width:100%;&nbsp; &nbsp; height:100%;&nbsp; &nbsp; margin:0 auto;&nbsp; padding:0;&nbsp; &nbsp; display:block;}#wrap-landing{&nbsp; &nbsp; position:relative;&nbsp; &nbsp; margin:0 auto;&nbsp; padding:0;&nbsp; &nbsp; content:url(https://i.imgur.com/gb6EyHk.png);&nbsp; &nbsp; width:1920px;&nbsp; &nbsp; height:1080px;}<!DOCTYPE html><html><head>&nbsp; <title></title></head><body>&nbsp; <div id="page">&nbsp; &nbsp; <div id="wrap-landing">&nbsp; &nbsp; </div>&nbsp; </div></body></html>

海绵宝宝撒

数学是:centerX = (el.scrollWidth - el.clientWidth) / 2可滚动#page元素的示例:const el = (sel, par) => (par || document).querySelector(sel);const elPage = el("#page");const centerX = (elPage.scrollWidth - elPage.clientWidth) / 2;const centerY = (elPage.scrollHeight - elPage.clientHeight) / 2;elPage.scrollTo(centerX, centerY);#page {&nbsp; display: flex;&nbsp; overflow: scroll;&nbsp;&nbsp; height: 200px;}#image {&nbsp; flex: 0 0 auto;&nbsp; margin: auto;&nbsp; content: url(https://i.imgur.com/gb6EyHk.png);&nbsp; width: 1920px;&nbsp; height: 1080px;}/*PS: flex and margin:auto is used to center&nbsp;#image in case is smaller than the parent.*/<div id="page">&nbsp; <div id="image"></div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript