Html5筆記(3)概述

使用Selectors API簡化選取操作

一、以前用來查找元素的JavaScript方法

函數 描述 示例
getElementById() 根據指定的id屬性值查找並返回元素 <div id="foo">
getElementById("foo");
getElementsByName() 返回所有name屬性爲指定值的元素  <input type="text" name="foo">
getElementsByName("foo");
getElementsByTagName()  返回所有標籤名稱與指定值相匹配的元素 <input type="text">
getElementsByTagName("input");

二、新QuerySelector方法

函數 描述 示例 結果
querySelector() 根據指定的選擇規則,
返回在頁面中找到的第一個匹配元素
querySelector("input.error"); 返回第一個CSS類名爲"error"的
文本輸入框
querySelectorAll() 根據指定規則返回頁面中所有相匹配的元素 querySelectorAll
("#results td");
返回id值爲results的元素下所有
的單元格


三、示例

使用Selector API獲取鼠標當前在哪個單元格上

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Query Selector Demo</title>

<style type="text/css">
td
{
	border-style:solid;
	border-width:1px;
	font-Size:300%;
}

td:hover
{
	background-color:cyan;
}

#hoverResult
{
	color:green;
	font-Size:200%;
}
</style>
</head>

<body>
<section>
<!--創建一個3行3列的表-->
<table>
<tr>
<td>A1</td> <td>A2</td> <td>A3</td>
</tr>
<tr>
<td>B1</td> <td>B2</td> <td>B3</td>
</tr>
<tr>
<td>C1</td> <td>C2</td> <td>C3</td>
</tr>
</table>

<div>
Focus the button,hover over the table cells,and hit Enter to
identify them using querySelector('td:hover').
</div> 
<button type="button" id="findHover" antofocus>Find 'td:hover' target</button>
<div id="hoverResult"></div>

<script type="text/javascript">
document.getElementById("findHover").οnclick=function()
{
	//找出頁面中的單元格
	var hovered=document.querySelector("td:hover");
	if(hovered)
	document.getElementById("hoverResult").innerHTML=hovered.innerHTML;
}
</script>
</section>
</body>
</html>

效果如下



發佈了88 篇原創文章 · 獲贊 6 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章