JavaScript与页面交互

JavaScript与页面交互联系首先要与html标签建立联系,下面来看几种关联标签的方法。

1.通过标签id来关联标签:

<body>
<h2 id="hh">数据类型</h2>
</body>

<script>
    let h2=document.getElementById('hh');
    console.log(h2);
   console.log(hh);  id是标签的唯一标识 所以也可以通过id直接拿到标签
</script>

==>
<h2 id="hh">
<h2 id="hh">

2.通过标签类来关联标签:

<body>
<h3 class="hh">wozhuini </h3>
<h3 class="hh">savjsvb</h3>

</body>

<script>
    let h3=document.getElementsByClassName('hh');
    console.log(h3)
    console.log(h3[0]);   拿到多个标签的情况下可以通过索引取值拿到想要的标签
</script>

==>
HTMLCollection [ h3.hh, h3.hh]
<h3 class="hh">

3.同css选择器选定标签:

<body>
<h2 id="hh">数据类型</h2>
<h3 class="hh3">wozhuini </h3>
<h3 class="hh3">savjsvb</h3>

</body>
<script>
h1=document.querySelector('body h2#hh');
//查找body标签下id为hh的h2标签 console.log(h1);
h2
=document.querySelector('#hh `.hh3 ');
//查找id为hh标签的兄弟标签中类名为hh3的标签 querySelector只找一个 console.log(h2);
h3
=document.querySelector('#hh` .hh3');
querySelector查找符合要求的所有标签 console.log(h3);

h4=document.querySelector('.hh3:nth-of-type(2))
//同样可以通过id、class或标签来定位一个或多个标签
</script>

通过上面的方法我们可以找到想要的某个标签,通过这些标签可以去获得、修改标签的样式、内容。属性等。

获得样式、内容、标签

<body>
<h2 id="hh">数据类型</h2>
<h3 class="hh3">wozhuini </h3>
<h3 class="hh3">savjsvb</h3>

</body>

<script>
let h1=document.querySelector('#hh');
let fontsize=h1.style.fontsize console.log(fontsize);
let backgroundColor=getComputedStyle(h1,null).backgroundColor;
getComputedStyle(ele_name,伪类选择器通常用null填充)能获得所有样式内联外联都可以 console.log(backgroundColor);
</script>

修改样式、内容、标签

<body>
<h2 id="hh">数据类型</h2>
<h3 class="hh3">wozhuini </h3>
<h3 class="hh3">savjsvb</h3>

</body>

<script>
    let h1=document.querySelector('h2');
    h1.style.color='red';
    h1.style.borderRadius='50%'
   //js可以直接改变样式 但是修改的只能是行间式
  h1.innerText='123456'      直接修改标签内容
  h1.innerHTML='<i>123456</i>'  修改标签
  
</script>

猜你喜欢

转载自www.cnblogs.com/duGD/p/11135135.html