aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/element/scrollleft/index.html
blob: 98fd329358431c1eb3ac2ed8e7b1e874aa225162 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
---
title: Element.scrollLeft
slug: Web/API/Element/scrollLeft
tags:
  - API
  - scrollLeft
translation_of: Web/API/Element/scrollLeft
---
<p>{{ APIRef("DOM") }}</p>

<p><strong><code>Element.scrollLeft</code></strong> 属性可以读取或设置元素滚动条到元素左边的距离。</p>

<p>注意如果这个元素的内容排列方向({{cssxref("direction")}}) 是<code>rtl</code> (right-to-left) ,那么滚动条会位于最右侧(内容开始处),并且<code>scrollLeft</code>值为0。此时,当你从右到左拖动滚动条时,scrollLeft会从0变为负数。</p>

<div class="blockIndicator warning">
<p>在使用显示比例缩放的系统上,<code>scrollLeft</code> 可能会是一个小数。</p>
</div>

<h2 id="Syntax_and_values" name="Syntax_and_values">语法</h2>

<pre class="eval">//获取滚动条到元素左边的距离
var <var>sLeft</var> = <var>element</var>.scrollLeft;
</pre>

<p><code>sLeft</code>是一个整数,代表元素滚动条距离元素左边多少像素。</p>

<pre class="eval">//设置滚动条滚动了多少像素
<var>element</var>.scrollLeft = 10;
</pre>

<p><code>scrollLeft</code> 可以是任意整数,然而:</p>

<ul>
 <li>如果元素不能滚动(比如:元素没有溢出),那么<code>scrollLeft</code> 的值是0。</li>
 <li>如果给<code>scrollLeft</code> 设置的值小于0,那么<code>scrollLeft</code> 的值将变为0。</li>
 <li>如果给<code>scrollLeft</code> 设置的值大于元素内容最大宽度,那么<code>scrollLeft</code> 的值将被设为元素最大宽度。</li>
</ul>

<h2 id="示例">示例</h2>

<h3 id="HTML">HTML</h3>

<pre class="brush: html">&lt;div id="container"&gt;
  &lt;div id="content"&gt;Click the button to slide right!&lt;/div&gt;
&lt;/div&gt;

&lt;button id="slide" type="button"&gt;Slide right&lt;/button&gt;</pre>

<h3 id="CSS">CSS</h3>

<pre class="brush: css">#container {
  width: 100px;
  height: 100px;
  border: 1px solid #ccc;
  overflow-x: scroll;
}

#content {
  width: 250px;
  background-color: #ccc;
}</pre>

<h3 id="JavaScript">JavaScript</h3>

<pre class="brush: js">const button = document.getElementById('slide');

button.onclick = function () {
  document.getElementById('container').scrollLeft += 20;
};</pre>

<h3 id="结构">结构</h3>

<p>{{EmbedLiveSample("示例")}}</p>

<h2 id="规范">规范</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('CSSOM View', '#dom-element-scrollleft', 'scrollLeft')}}</td>
   <td>{{Spec2("CSSOM View")}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容">浏览器兼容</h2>

<p>{{Compat("api.Element.scrollLeft")}}</p>

<h2 id="参见">参见</h2>

<ul>
 <li><a href="https://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx" title="MSDN Measuring Element Dimension and Location">MSDN's Measuring Element Dimension and Location</a></li>
 <li>{{domxref("Element.scrollTop")}}</li>
 <li>{{domxref("Element.scrollTo()")}}</li>
</ul>