Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript DOM으로 배경 이미지 시작 위치 설정하는 방법

JavaScript로 배경 이미지의 시작 위치를 설정하려면 backgroundPosition 속성을 사용하면 됩니다. 이 속성을 활용하면 요소 안에서 배경 이미지가 어디에 표시될지 원하는 위치로 자유롭게 지정할 수 있습니다.

사용할 수 있는 위치 값

backgroundPosition 속성에는 "top", "bottom", "left", "right", "center"와 같은 키워드 조합을 사용할 수 있으며, 픽셀(px)이나 퍼센트(%) 단위의 수치도 지원합니다. 예를 들어 "top right"는 이미지를 오른쪽 상단에 배치하고, "center"는 정중앙에 배치합니다.

예제

아래 코드를 실행한 뒤 버튼을 클릭해 보세요. 배경 이미지가 설정되면서 화면 오른쪽 상단에 나타나는 것을 확인할 수 있습니다.

<!DOCTYPE html>
<html>
   <head>
      <style>
         body {
            background-repeat: no-repeat;
         }
      </style>
   </head>
   <body>
      <button onclick="display()">배경 이미지 설정하기</button>
      <script>
         function display() {
            document.body.style.backgroundImage = "url('https://www.tutorialspoint.com/html5/images/html5-mini-logo.jpg')";
            document.body.style.backgroundPosition = "top right";
         }
      </script>
   </body>
</html>