javascript - 怎么分别改变用JS创建出来的元素的样式?

查看:90
本文介绍了javascript - 怎么分别改变用JS创建出来的元素的样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    div {height: 150px; width: 150px; border: 1px solid #000; margin: 5px;}
    </style>
</head>
<body>
    <button>new div</button>
</body>
<script>
    var body = document.querySelector("body");
    var btn = document.querySelector("button"); // 获取body和按钮
    btn.onclick = function(){
        div = document.createElement("div");
        button1 = document.createElement("button");
        button2 = document.createElement("button"); // 创建div和两个按钮
        button1.innerHTML = "change With";
        button2.innerHTML = "change Height"; // 设置两个按钮的内容
        body.appendChild(div);
        body.appendChild(button1);
        body.appendChild(button2); //把div和两个按钮插入进文档
        // code...
        // 我想点击按钮改变div相应的样式...
    }
</script>
</html>

点击new div的按钮可以创建出来一个div和两个按钮;
我想点击按钮就可以改变相应的div样式。
例:
点击第一组changeWith和changeHeight按钮,就改变第一个div的宽高。

而且同时有多个div存在的情况下,按钮的功能不冲突。

这个应该怎么写?
或者说思路是怎么样的?

解决方案

这种情况可以使用面向对象的思想去管理,每一组div button1 button2 都看成一个Button对象
将操作行为封装在对象里面。每次点击按钮都创建一个对象就可以了

function Button(div, button1, button2) {
      this.div = div;
      this.button1 = button1;
      this.button2 = button2;
      this.init();
  }
  Button.prototype.init = function() {
      var _this = this
      this.button2.onclick = function() {
          _this.changeHeight(100)
      }
      this.button1.onclick = function() {
          _this.changeWidth(200)
      }
  }
  Button.prototype.changeHeight = function(height) {
      console.log(height)
      this.div.style.height = height + 'px'
  }
  Button.prototype.changeWidth = function(width) {
      this.div.style.width = width + 'px'
  }

在这个地方创建对象

body.appendChild(button2); //把div和两个按钮插入进文档
      new Button(div, button1, button2)
      // code...
      // 我想点击按钮改变div相应的样式...

这篇关于javascript - 怎么分别改变用JS创建出来的元素的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆