Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

css - Set scrollTop and scrollLeft without JavaScript

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:

<div scrollLeft="300" scrollTop="200"></div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm afraid that this is not possible using CSS/HTML only.

Edit [05.01.2012] - A possible solution

I created a solution that works in the following browsers:

  • Firefox 4+
  • Safari 5+
  • Chrome 6+
  • Opera 11+
  • IE 10+
  • Android 2.3+

It's really a bit hacky, so see whether you would use it or not. :)

A little explanation

I used the HTML5 attribute autofocus on 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: none as this won't trigger the autofocus (only tested this in Safari).

Demo

The demo will run in Safari and Chrome only. IE and Firefox seem to not fire autofocus in an <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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...