[英]Set scrollTop and scrollLeft without JavaScript
I have a question about the scrollTop
and scrollLeft
properties.我有一个关于
scrollTop
和scrollLeft
属性的问题。 I would like to set these properties in my div without using JavaScript (jQuery).我想在不使用 JavaScript (jQuery) 的情况下在我的 div 中设置这些属性。 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.我的问题是,我有一个解释 HTML 代码的程序,当程序解释代码时,我滚动的 div 的值为零。 The program can't read the
scrollTop
or scrollLeft
value.程序无法读取
scrollTop
或scrollLeft
值。 Exists a HTML-tag like:存在一个 HTML 标签,如:
<div scrollLeft="300" scrollTop="200"></div>
I'm afraid that this is not possible using CSS/HTML only.恐怕仅使用 CSS/HTML 是不可能的。
I created a solution that works in the following browsers:我创建了一个适用于以下浏览器的解决方案:
It's really a bit hacky, so see whether you would use it or not.它真的有点hacky,所以看看你是否会使用它。 :)
:)
A little explanation一点解释
I used the HTML5 attribute autofocus
on an <input>
-field.我在
<input>
字段上使用了 HTML5 属性autofocus
。 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.
但这仍然迫使 Safari 有一个闪烁的像素,所以我用跨度来解决这个问题,它就像一个叠加层。 Note that you can't simply use
display: none
as this won't trigger the autofocus (only tested this in Safari).请注意,您不能简单地使用
display: none
因为这不会触发自动对焦(仅在 Safari 中测试过)。
Demo演示
The demo will run in Safari and Chrome only.该演示将仅在 Safari 和 Chrome 中运行。 IE and Firefox seem to not fire autofocus in an
<iframe>
. 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.