คุณสมบัติ clip ใช้สำหรับกำหนดหรือดึงค่าส่วนที่มองเห็นขององค์ประกอบที่มี position: absolute หรือ position: fixed (ทำงานเฉพาะองค์ประกอบ positioned)
ไวยากรณ์ (Syntax)
object.style.clip = "auto|rect(top, right, bottom, left)|initial|inherit"
ค่าที่รองรับ
| ค่า | คำอธิบาย |
|---|---|
| auto | ไม่ตัดครอป (ค่าเริ่มต้น) |
| rect(top, right, bottom, left) | ตัดครอปตามพิกัด 4 จุด (จากขอบบนขององค์ประกอบ) |
| initial | ตั้งค่ากลับเป็นค่าเริ่มต้น |
| inherit | สืบทอดจากพาเรนต์ |
ตัวอย่างการใช้งาน
<!DOCTYPE html>
<html>
<head>
<style>
div { position: relative; }
#IMG1 {
width: 200px;
height: 200px;
position: absolute;
}
#P1 {
position: absolute;
margin-top: 210px;
}
button { margin-top: 250px; }
</style>
<script>
function changeClip() {
document.getElementById("IMG1").style.clip = "rect(0px, 75px, 75px, 0px)";
document.getElementById("Sample").innerHTML = "คุณสมบัติ clip ของรูปภาพถูกเปลี่ยนแล้ว";
}
</script>
</head>
<body>
<div>
<img id="IMG1" src="https://www.tutorialspoint.com/hibernate/images/hibernate-mini-logo.jpg" alt="Hibernate Logo">
<p id="P1">คลิกปุ่มเพื่อเปลี่ยนคุณสมบัติ clip ของรูปภาพด้านบน</p>
<button onclick="changeClip()">เปลี่ยน Clip</button>
<p id="Sample"></p>
</div>
</body>
</html>
ผลลัพธ์
ก่อน: แสดงรูปภาพเต็ม 200x200px
หลัง: แสดงเฉพาะพื้นที่ rect(0, 75, 75, 0) = มุมซ้ายบน 75x75px
⚠️ สถานะ: Deprecated (เลิกใช้แล้ว)
clip ถูก deprecated แล้ว** ให้ใช้ clip-path แทน ซึ่งมีความสามารถมากกว่า:
เปรียบเทียบ clip vs clip-path
| คุณสมบัติ | clip | clip-path |
|---|---|---|
| รองรับรูปร่าง | เฉพาะสี่เหลี่ยม (rect) | วงกลม, เบซิเออร์, พอลิгон, SVG path |
| ต้อง position | absolute/fixed เท่านั้น | ไม่จำเป็น (ทำงานกับทุก display) |
| หน่วย | px เท่านั้น | px, %, rem, em, calc() |
| Animation | จำกัด | รองรับเต็มที่ |
| สถานะ | Deprecated | Standard (แนะนำ) |
ตัวอย่าง clip-path (แนะนำ)
.circle-crop {
clip-path: circle(50% at center);
}
.polygon-crop {
clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%); /* รูปเพชร */
}
.svg-path {
clip-path: url(#myClipPath); /* ใช้ SVG clipPath */
}
การรองรับเบราว์เซอร์
- clip: ทุกเบราว์เซอร์ (แต่ deprecated)
- clip-path: Chrome 24+, Firefox 3.5+, Safari 7+, Edge 12+ (ต้อง -webkit- prefix เก่าๆ)