没有javascript设置scrollTop和scrollLeft

时间:2013-01-03 12:36:37

标签: javascript css scrolltop

我对scrollTop和scrollLeft属性有疑问。我想在我的div中设置这些属性而不使用JavaScript(jquery)。这可能吗? 我的问题是,我有一个解释HTML代码的程序,当程序解释代码时,我滚动的div的值为零。程序无法读取scrollTop或scrollLeft值。存在HTML标记,如:

<div scrollLeft="300" scrollTop="200"></div>

1 个答案:

答案 0 :(得分:37)

我担心仅使用CSS / HTML无法做到这一点。

编辑[05.01.2012] - 可能的解决方案

我创建了一个适用于以下浏览器的解决方案:

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

这真的有点hacky,所以看看你是否会使用它。 :)

一点解释

我在autofocus字段上使用了HTML5属性<input>。由于这将聚焦输入,因此必须将其输入视口。因此它将滚动到给定的位置。要删除突出显示的轮廓并且根本看不到输入,您必须设置一些样式。但这仍然迫使Safari有一个闪烁的像素,所以我用跨度做了伎俩,就像覆盖一样。请注意,您不能简单地使用display: none,因为这不会触发自动对焦(仅在Safari中对此进行了测试)。

<强>演示

Try before buy

该演示仅在Safari和Chrome中运行。 IE和Firefox似乎没有在<iframe>中激活自动对焦。

<强> CSS

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;
}

<强> HTML

<div class="outer">  
    <div class="inner">
        <input type="text" autofocus></input>
        <span></span>
    </div>
</div>