HTMLImageElement: x 屬性
只讀的 HTMLImageElement 屬性 x 表示 <img> 元素的左邊框相對於根元素原點的 x 座標。
僅當影像的 display 屬性計算值為 table-column 或 table-column-group 時,x 和 y 屬性才對影像有效。換句話說:該值要麼直接顯式地設定在它上面,要麼是從包含元素繼承而來,要麼是透過位於由 <col> 或 <colgroup> 描述的列中。
值
一個整數值,表示從元素最近的根元素的左邊緣到 <img> 元素的邊框盒左邊緣的距離(以畫素為單位)。最近的根元素是包含該影像的最外層 <html> 元素。如果影像位於 <iframe> 中,則其 x 值相對於該框架。
在下面的圖表中,左邊框邊緣是藍色填充區域的左邊緣。因此,x 返回的值將是該點到內容區域左邊緣的距離。

注意: 僅當影像的 display 屬性的計算值為 table-column 或 table-column-group 時,x 屬性才有效;換句話說,這其中一個值直接設定在 <img> 元素上,或者從包含元素繼承而來,或者透過位於由 <col> 或 <colgroup> 描述的列中。
示例
下面的示例演示了 HTMLImageElement 屬性 x 和 y 的用法。
HTML
在此示例中,我們看到一個表格,其中顯示了網站使用者的資訊,包括他們的使用者 ID、全名和頭像影像。
<table id="userinfo">
<colgroup>
<col span="2" class="group1" />
<col />
</colgroup>
<tr>
<th>UserID</th>
<th>Name</th>
<th>Avatar</th>
</tr>
<tr>
<td>12345678</td>
<td>Johnny Rocket</td>
<td>
<img src="/shared-assets/images/examples/grapefruit-slice.jpg" />
</td>
</tr>
</table>
<pre id="log"></pre>
JavaScript
獲取表格中的影像並查詢其 x 和 y 值的 JavaScript 程式碼如下。
const logBox = document.querySelector("pre");
const tbl = document.getElementById("userinfo");
const log = (msg) => {
logBox.innerText += `${msg}\n`;
};
const cell = tbl.rows[1].cells[2];
const image = cell.querySelector("img");
log(`Image's global X: ${image.x}`);
log(`Image's global Y: ${image.y}`);
這使用了 <table> 的 rows 屬性來獲取表格中的行列表,然後查詢第 1 行(由於是零基索引,表示從頂部數起的第二行)。然後,它檢視該 <tr>(表格行)元素的 cells 屬性來獲取該行中的單元格列表。從該行中獲取第三個單元格(再次,指定 2 作為零基偏移量)。
然後,我們可以透過在代表該單元格的 HTMLTableCellElement 上呼叫 querySelector() 來獲取單元格本身的 <img> 元素。
最後,我們可以查詢並顯示 HTMLImageElement 的 x 和 y 屬性的值。
CSS
定義表格外觀的 CSS
.group1 {
background-color: #d7d9f2;
}
table {
border-collapse: collapse;
border: 2px solid rgb(100 100 100);
font-family: sans-serif;
}
td,
th {
border: 1px solid rgb(100 100 100);
padding: 10px 14px;
}
td > img {
max-width: 4em;
}
結果
生成的表格外觀如下
規範
| 規範 |
|---|
| CSSOM 檢視模組 # dom-htmlimageelement-x |
瀏覽器相容性
載入中…