【问题标题】:target child div of ID in JavaScript and CSSJavaScript 和 CSS 中 ID 的目标子 div
【发布时间】:2022-11-02 18:50:54
【问题描述】:

我很难定位id="videoContainer" 的子 div 并更改其样式

<div id="videoContainer">
  <div style="width: 640px; height: 360px">   <------- target this
    <video
      src=""
      preload="auto"
      autoplay=""
      style="width: 100%; height: 100%"
    ></video>
  </div>
</div>


const videoContainer = document.getElementById('videoContainer')
document.getElementById('videoContainer').children?.[0]?.setAttribute("style", `width: 150px; height: 200px;`);

【问题讨论】:

  • document.querySelector('#videoContainer &gt; div') 允许您直接针对孩子div

标签: javascript html css ecmascript-6


【解决方案1】:

我会用 CSS 来做,但如果你必须使用 JS:

<div id="videoContainer">
  <div style="width: 640px; height: 360px">   <------- target this
    <video
      src=""
      preload="auto"
      autoplay=""
      style="width: 100%; height: 100%"
    ></video>
  </div>
</div>


const videoContainer = document.getElementById("videoContainer");
videoContainer.style.width = "640px";
videoContainer.style.height = "360px";

【讨论】:

    【解决方案2】:

    您可以将 querySelector 与直接子 &gt; 和第一个 :first-child 一起使用,如下所示:

    const videoContainer = document.querySelector('#videoContainer > div:first-child')
    videoContainer.style.width =  "150px"
    videoContainer.style.height = "200px"
    videoContainer.textContent = videoContainer.style.width
    <div id="videoContainer">
      <div style="width: 640px; height: 360px">   <!------- target this -->
       video here
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 2019-09-11
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      • 2011-07-04
      • 1970-01-01
      相关资源
      最近更新 更多