ใช้อ้างถึง Element ต่างๆในหน้า
*
: เลือกทุกตัว.class
: Class#id
: IDtag
: Tag
.a, .b
: เลือกตัวที่มี.a
หรือ.b
อย่างน้อย 1 ตัว.a.b
: เลือก Element ที่มี.a
และ.b
อยู่ร่วมกัน.a > .b
: เลือก.b
ที่เป็นลูก(child)ของ.a
a[attr]
: เลือกa
ที่มี Attributeattr
อยู่a[attr='x']
: เลือกa
ที่ Attributeattr
มีค่าเป็นx
a[attr^='x']
: เลือกa
ที่ Attributeattr
ขี้นต้นเป็นx
a[attr$='x']
: เลือกa
ที่ Attributeattr
ลงท้ายเป็นx
p:first-child
: เลือกp
ตัวแรกp:last-child
: เลือกp
ตัวสุดท้ายp:nth-child(2)
: เลือกp
ตัวที่สองp:nth-child(odd)
: เลือกp
ทุกตัวที่ลำดับเป็นคี่ (คู่ใช่even
)p:nth-child(2n)
: เลือกp
ทุกตัวที่ลำดับหารสองลงตัว (เลือกทุกๆสองตัว)
a:hover
: เลือกa
ขนะเมาส์ชี้อยู่a:active
: เลือกa
ขนะเมาส์คลิกอยู่
<link rel="stylesheet" type="text/css" href="ไฟล์.css">
<script src="ไฟล์.js"></script>
ใช้ในกรณีที่หน้ามีภาษาไทยแล้วแสดงผลไม่ได้
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
onclick
: ตอนที่ถูกคลิกonmouseover
: ตอนที่นำเคอร์เซอร์ไปวางonkeydown
: ตอนที่กดปุ่มบนแป้นพิมพ์ใดๆ
<button onclick="alert('Clicked');">Click me!</button> //จะมี Alert ขึ้นมาตอนกดปุ่ม
<a onclick="alert('Hovered');">Hover me!</a> //จะมี Alert ขึ้นมาตอนเคอร์เซอร์อยู่เหนือตัวหนังสือ
<textarea onkeydown="alert('Pressed');"></textarea> //จะมี Alert ขึ้นมาตอนมีการกดปุ่มบนแป้นพิมพ์ใดๆใน textarea นี้
selector{
property: value;
}
element{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
document.querySelector('ใส่ Selector เหมือนหัวข้อบน');
innerText
: เฉพาะตัวหนังสือinnerHTML
: แทกต่างๆด้วย
<div id="example">
<b>Hello World</b>
</div>
document.querySelector('#example').innerText; //จะได้ค่าเป็น Hello World
document.querySelector('#example').innerHTML; //จะได้ค่าเป็น <b>Hello World</b>
<div id="example">
<b>Hello World</b>
</div>
document.querySelector('#example').innerText = 'Hello Earth'; //จะได้ค่าเป็น Hello Earth ตัวหนาเหมือนเดิม
document.querySelector('#example').innerHTML = 'Hello Earth'; //จะได้ค่าเป็น Hello Earth ที่ไม่เป็นตัวหนา
getAttrbute()
: ดึงค่าsetAttrbute()
: เปลี่ยนค่า
<div id="example" status="ok"></div>
document.querySelector('#example').getAttribute('status'); //จะได้ค่าเป็น ok
document.querySelector('#example').setAttribute('status', 'nein'); //ค่าของ status ใน #example จะกลายเป็น nein (<div id="example" status="nein"></div>)
.style.property = newstyle;
<div id="example">Planet Earth is blue, And there's nothing I can do</div>
document.querySelector('#example').style.color = 'red'; //ตัวหนังสือใน div ก็จะเปลี่ยนเป็นสีแดง
เมื่อกด space
(32) จะมี Alert ขึ้น
document.onkeypress = function (e) {
e = e || window.event;
if(e.keycode == 32){
alert('Space pressed!');
}
};