Computer >> Máy Tính >  >> Lập trình >> Javascript

Phải làm gì khi văn bản tràn phần tử chứa bằng JavaScript?


Sử dụng textOverflow thuộc tính để chống lại sự cố tràn văn bản. Thêm dấu chấm lửng nếu văn bản tràn phần tử chứa.

Ví dụ

Bạn có thể thử chạy đoạn mã sau để tìm hiểu việc cần làm khi văn bản làm tràn phần tử chứa bằng JavaScript -

<!DOCTYPE html>
<html>
   <head>
      <style>
         #myID {
            border: 2px solid blue;
            background-color: gray;
            overflow: hidden;
            text-overflow: visible;
            width: 200px;
            white-space: nowrap;
         }
      </style>
   </head>
   <body>
      <button onclick = "display()"> Click </button>
      <div id = "myID">
         This is Demo Text! This is Demo Text! This is Demo Text!<br>
         This is Demo Text! This is Demo Text! This is Demo Text!<br>
         This is Demo Text! This is Demo Text! This is Demo Text!<br>
         This is Demo Text! This is Demo Text! This is Demo Text!<br>
      </div>
      <script>
         function display() {
            document.getElementById("myID").style.textOverflow = "ellipsis";
         }
      </script>
   </body>
</html>