Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีตั้งคาความกว้างเส้นขอบขวา (Right Border Width) ด้วย JavaScript


บทนำ

ในการเปลี่ยนความกว้างของเส้นขอบขวาขององค์ประกอบ HTML ผ่าน JavaScript เราใช้คุณสมบัติ borderRightWidth ของอ็อบเจกต์ style คุณสมบัตินี้รับค่าเดียวกับ CSS border-width เช่น thin, medium, thick หรือค่าความยาวที่ระบุหน่วยได้ (px, em, rem, vw, ฯลฯ)

ตัวอย่างโค้ดครบถ้วน

<!DOCTYPE html>
<html>
<head>
  <style>
    #box {
      border: thick solid blue;
      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="changeRightBorderWidth()">เปลี่ยนความกว้างขอบขวาเป็น 10px</button>

  <script>
    function changeRightBorderWidth() {
      document.getElementById("box").style.borderRightWidth = "10px";
    }
  </script>
</body>
</html>

ค่าที่ใช้ได้สำหรับ borderRightWidth

ประเภทค่า ตัวอย่าง คำอธิบาย
Keywordthin, medium, thickความหนามาตรฐานของเบราว์เซอร์ (medium ≈ 3-4px)
Length (px)1px, 5px, 10pxค่าคงที่ในพิกเซล
Length (em/rem)0.5em, 1remสัมพันธ์กับขนาดฟอนต์
Length (viewport)2vw, 1vhสัมพันธ์กับขนาด viewport
Globalinherit, initial, unset, revertควบคุมการสืบทอด/รีเซ็ตค่า

คุณสมบัติที่เกี่ยวข้อง

  • borderRightStyle - รูปแบบเส้นขอบขวา (solid, dashed, ฯลฯ)
  • borderRightColor - สีเส้นขอบขวา
  • borderRight - Shorthand ตั้งค่าทั้ง 3 พร้อมกัน: "10px dashed red"
  • borderWidth - ตั้งค่าความกว้างทั้ง 4 ด้าน

ตัวอย่างใช้ Shorthand borderRight

// ตั้งค่าความกว้าง รูปแบบ และสีพร้อมกัน
element.style.borderRight = "3px dotted green";

// อ่านค่าปัจจุบัน
var currentWidth = element.style.borderRightWidth; // "3px" (string)
var computedWidth = getComputedStyle(element).borderRightWidth; // "3px" (ค่าจริงที่เรนเดอร์)

หมายเหตุ

  • ค่าที่ตั้งผ่าน style.borderRightWidth จะเป็น Inline Style มีความสำคัญสูงกว่า CSS Class
  • หากต้องการอ่านค่าที่คำนวณจริง (Computed Style) ให้ใช้ getComputedStyle(element).borderRightWidth
  • รองรับในทุกเบราว์เซอร์สมัยใหม่ (IE9+)