在没有 javascript 的情况下设置 scrollTop 和 scrollLeft
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14139091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
set scrollTop and scrollLeft without javascript
提问by Yetispapa
I have a question about the scrollTop and scrollLeft properties. I would like to set these properties in my div without using JavaScript (jquery). Is this possible? My problem is, I have a program which interprets the HTML code and the divs which I scrolled have the value zero when the program interpret the code. The program can't read the scrollTop or scrollLeft value. Exists a HTML-tag like:
我有一个关于 scrollTop 和 scrollLeft 属性的问题。我想在不使用 JavaScript (jquery) 的情况下在我的 div 中设置这些属性。这可能吗?我的问题是,我有一个解释 HTML 代码的程序,当程序解释代码时,我滚动的 div 的值为零。程序无法读取 scrollTop 或 scrollLeft 值。存在一个 HTML 标签,如:
<div scrollLeft="300" scrollTop="200"></div>
回答by insertusernamehere
I'm afraid that this is not possible using CSS/HTML only.
恐怕仅使用 CSS/HTML 是不可能的。
Edit [05.01.2012] - A possible solution
编辑 [05.01.2012] - 一个可能的解决方案
I created a solution that works in the following browsers:
我创建了一个适用于以下浏览器的解决方案:
- Firefox 4+
- Safari 5+
- Chrome 6+
- Opera 11+
- IE 10+
- Android 2.3+
- 火狐 4+
- Safari 5+
- 铬 6+
- 歌剧 11+
- 浏览器 10+
- 安卓 2.3+
It's really a bit hacky, so see whether you would use it or not. :)
它真的有点hacky,所以看看你是否会使用它。:)
A little explanation
一点解释
I used the HTML5 attribute autofocuson an <input>-field. As this will focus the input, it has to get it into the viewport. Therefor it will scroll to the given position. To get rid of the highlighted outline and to not see the input at all, you have to set some styles. But this still forced Safari to have one blinking pixel, so I did the trick with the span, that acts like an overlay. Note that you can't simply use display: noneas this won't trigger the autofocus (only tested this in Safari).
我autofocus在<input>-field上使用了 HTML5 属性。由于这将聚焦输入,因此必须将其放入视口。因此它将滚动到给定的位置。要摆脱突出显示的轮廓并且根本看不到输入,您必须设置一些样式。但这仍然迫使 Safari 有一个闪烁的像素,所以我用跨度来解决这个问题,它就像一个叠加层。请注意,您不能简单地使用,display: none因为这不会触发自动对焦(仅在 Safari 中测试过)。
Demo
演示
The demo will run in Safari and Chrome only. IE and Firefox seem to not fire autofocus in an <iframe>.
该演示将仅在 Safari 和 Chrome 中运行。IE 和 Firefox 似乎不会在<iframe>.
div.outer {
height: 100px;
width: 100px;
overflow: auto;
}
div.inner {
position: relative;
height: 500px;
width: 500px;
}
div.inner>input {
width: 1px;
height: 1px;
position: absolute;
z-index: 0;
top: 300px;
left: 200px;
border: 0;
outline: 0;
}
div.inner>span {
width: 1px;
height: 1px;
position: absolute;
z-index: 1;
top: 300px;
left: 200px;
background: white;
}
<div class="outer">
<div class="inner">
<input type="text" autofocus></input>
<span></span>
</div>
</div>

