บทนำ
ในการเปลี่ยนรูปแบบเส้นขอบขวาขององค์ประกอบ HTML ผ่าน JavaScript เราใช้คุณสมบัติ borderRightStyle ของอ็อบเจกต์ style คุณสมบัตินี้รับค่ารูปแบบเส้นขอบเดียวกับ CSS เช่น solid, dashed, dotted, double, groove, ridge, inset, outset, none, หรือ hidden
ตัวอย่างโค้ดครบถ้วน
<!DOCTYPE html>
<html>
<head>
<style>
#box {
border: thick solid gray;
width: 300px;
height: 300px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.2rem;
margin-bottom: 15px;
}
</style>
</head>
<body>
<div id="box">Demo Text</div>
<button type="button" onclick="changeRightBorderStyle()">เปลี่ยนเส้นขอบขวาเป็น Dashed</button>
<script>
function changeRightBorderStyle() {
document.getElementById("box").style.borderRightStyle = "dashed";
}
</script>
</body>
</html>
ค่าที่ใช้ได้สำหรับ borderRightStyle
| ค่า | ลักษณะ | รองรับ 3D Effect |
|---|---|---|
none | ไม่แสดงเส้นขอบ (ค่าเริ่มต้น) | ไม่ |
hidden | เหมือน none แต่優先ในตาราง (table collapse) | ไม่ |
solid | เส้นทึบธรรมดา | ไม่ |
dashed | เส้นขีดขาด | ไม่ |
dotted | เส้นจุด | ไม่ |
double | เส้นคู่ (ต้องมี width ≥ 3px) | ไม่ |
groove | เส้นขูดเข้า (3D) | ใช่ |
ridge | เส้นยื่นออก (3D) | ใช่ |
inset | เส้นขอบเข้า (3D) | ใช่ |
outset | เส้นขอบออก (3D) | ใช่ |
คุณสมบัติที่เกี่ยวข้อง
borderRightWidth- ความหนาของเส้นขอบขวาborderRightColor- สีของเส้นขอบขวาborderRight- Shorthand ตั้งค่าทั้งสามอย่างพร้อมกัน
ตัวอย่างใช้ Shorthand borderRight
// ตั้งค่าความกว้าง รูปแบบ และสีพร้อมกัน element.style.borderRight = "5px double purple"; // เปลี่ยนเฉพาะรูปแบบ คงค่าอื่นไว้ element.style.borderRightStyle = "groove";
การเข้าถึงค่าปัจจุบัน
// อ่านค่า Inline Style (ที่ตั้งผ่าน JS/HTML) var inlineStyle = element.style.borderRightStyle; // "dashed" หรือ "" // อ่านค่าที่เบราว์เซอร์เรนเดอร์จริง (Computed Style) var computedStyle = getComputedStyle(element).borderRightStyle; // "dashed" (เสมอ)
หมายเหตุ
borderRightStyleต้องมีค่าไม่ใช่noneหรือhiddenจึงจะเห็นเส้นขอบ (ต้องมี width > 0)- ค่า 3D (
groove,ridge,inset,outset) ต้องการborderRightColorที่ไม่ใช่สีเดียวกับพื้นหลังจึงจะเห็นเอฟเฟกต์ชัด - รองรับในทุกเบราว์เซอร์สมัยใหม่ (IE9+)