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

คุณสมบัติ HTML DOM Style backgroundPosition


คุณสมบัติ backgroundPosition ใช้สำหรับตั้งค่าหรือรับตำแหน่งเริ่มต้นของภาพพื้นหลังขององค์ประกอบ เทียบกับจุดกำเนิด (origin)

ไวยากรณ์ (Syntax)

object.style.backgroundPosition = value

ค่าที่ใช้ได้ (Values)

ค่า คำอธิบาย
top left
top center
top right
center left
center center
center right
bottom left
bottom center
bottom right
ตำแหน่งสามารถเข้าใจได้จากชื่อ หากระบุค่าเดียว อีกค่าจะเป็น center เสมอ
xpos ypos ระบุตำแหน่งแนวนอน (x) และแนวตั้ง (y) เริ่มจากมุมซ้ายบน 0,0 แนะนำให้ใช้หน่วยพิกเซล แต่อื่นๆ ก็ได้
x% y% ระบุตำแหน่งเป็นเปอร์เซ็นต์ แนวนอน (x) และแนวตั้ง (y) เริ่มจากมุมซ้ายบน 0% 0% ถึงมุมขวาล่าง 100% 100% หากระบุค่าเดียว อีกค่าจะเป็น center คือ 50%
initial ตั้งค่าคุณสมบัติให้เป็นค่าเริ่มต้น
inherit สืบทอดคุณสมบัตินี้จากองค์ประกอบพาเรนต์

ตัวอย่าง (Example)

<!DOCTYPE html> <html> <head> <style> 
  body{ 
    background-image: url("https://www.tutorialspoint.com/power_bi/images/power-bi-minilogo.jpg"); 
    background-repeat: no-repeat; 
    background-attachment: fixed; 
    background-position: 20% 60%; 
  } 
</style> 
<script> 
  function changeBackPosition(){ 
    document.body.style.backgroundPosition="top right"; 
    document.getElementById("Sample").innerHTML="The background image position is now changed"; 
  } 
</script> </head> 
<body> 
<h2>Learning is fun</h2> 
<p>Free learning tutorial for all...</p> 
<p>Change the background image position by clicking the below button.</p> 
<button onclick="changeBackPosition()">CHANGE POSITION</button> 
<p id="Sample"></p> 
</body> </html>

ผลลัพธ์ (Output)

ผลลัพธ์ที่ได้:

คุณสมบัติ HTML DOM Style backgroundPosition

เมื่อคลิกปุ่ม CHANGE POSITION:

คุณสมบัติ HTML DOM Style backgroundPosition