【问题标题】:Changing text color with JavaScript Object Constructor使用 JavaScript 对象构造函数更改文本颜色
【发布时间】:2019-05-03 02:52:42
【问题描述】:

我是这里的菜鸟,感谢一些关于我正在尝试解决的问题的建议。我意识到在不使用对象构造函数的情况下可能有更好的方法来做到这一点,但我正在努力更好地理解对象。我的问题是是否有类似 this.function 的东西引用了所有其他没有调用我的函数的对象。这是我想要完成的任务:

<!doctype HTML>
<html>

<head>
  <title>Test</title>
  <style type="text/css">
    a {
      text-decoration: none;
      color: black;
    }
    
    a:visited {
      text-decoration: none;
      color: black;
    }
  </style>
</head>

<body>
  <ul>
    <li><a href="#" id="one"> Test</a> </li>
    <li><a href="#" id="two"> Test again</a> </li>
    <li><a href="#" id="three">Tester </a></li>
    <li><a href="#" id="four"> Testify</a> </li>
  </ul>
  <script>
    var first = document.getElementById('one');
    var second = document.getElementById('two');
    var third = document.getElementById('three');
    var fourth = document.getElementById('four');

    var colorChange = function(theID) {
      this.id = theID;
      this.formatContent = () => {
        this.id.style.color = "red";
      };
    }

    test = new colorChange(first);
    testAgain = new colorChange(second);
    tester = new colorChange(third);
    testify = new colorChange(fourth);

    function createEventListeners() {
      if (first.addEventListener) {
        first.addEventListener("click", test.formatContent, false);
      }
      if (second.addEventListener) {
        second.addEventListener("click", testAgain.formatContent, false);
      }
      if (third.addEventListener) {
        third.addEventListener("click", tester.formatContent, false);
      }
      if (fourth.addEventListener) {
        fourth.addEventListener("click", testify.formatContent, false);
      }
    }

    function init() {
      createEventListeners();
    }

    if (window.addEventListener) {
      //call init() on page load
      console.log("> Adding TC39 Event Listener...");
      window.addEventListener("load", init, false);
    } else if (window.attachEvent) {
      console.log("> Adding MS Event Listener...");
      window.attachEvent("onload", init);
    }
  </script>
</body>

</html>

您会注意到,当您单击其中一个 li 项目时,它的颜色会变为红色。问题是,当您单击另一个 li 时,这并不清楚。我的想法是,我可以告诉浏览器在运行 formatContent() 时将所有其他对象更改为黑色。是否有捷径可寻?

如果需要,这里有一支笔:https://codepen.io/seanbarker182/pen/JexPVz

提前感谢您的帮助!

【问题讨论】:

  • 你还没有添加任何代码来清除它。
  • 是的,我意识到那里没有任何东西可以改变颜色,所以我不应该期望它在当前状态下清除。我希望得到一些关于清除它的最佳方法的建议。

标签: javascript jquery html css object


【解决方案1】:

只需更改您的formatContent 方法:

this.formatContent = () => {
    if (this.id.style.color == "black") {
        this.id.style.color = "red";
    } else {
        this.id.style.color = "black";
    }
};

编辑:

要只让被点击的那个变成红色,首先创建一个数组:

var elements = [first, second, third, fourth];

然后在函数中循环它并将它们全部设置为黑色:

this.formatContent = () => {
    elements.forEach(function(elem) {
        elem.style.color = "black";
    }
    this.id.style.color = "red";
};

【讨论】:

  • 感谢您的建议!当我添加它时,它不再更改任何文本颜色。编辑:实际上我做了一些更改,它确实将颜色更改为红色,如果我再次单击它,它会变回黑色。如果我点击“测试”,我想要它变成红色,但如果我点击“再次测试”,我希望它变成红色,“测试”变成黑色
  • 是的,这就是我为了让它工作而改变的,但我可能不清楚我想要完成什么。我在上面编辑了我的评论以澄清。基本上我希望它在 CSS 中表现得像 :active。
【解决方案2】:

如果您这样做是为了了解对象,使用prototype 是获得所需内容的一种方法:

var colorChange = function (theID) {
  this.id = theID;
  this.instances.push(this);
  this.formatContent = () => {
  this.revertColors();
  this.id.style.color = "red"
  };
}

colorChange.prototype.instances = [];
colorChange.prototype.revertColors = function() {
  this.instances.forEach(instance => (instance.id.style.color = "black"))
}

此代码将实例存储在 prototype 对象上,当您初始化它时,该对象由所有类实例共享。您可以从任何实例访问此数组并进行所需的修改。

var first = document.getElementById('one');
var second = document.getElementById('two');
var third = document.getElementById('three');
var fourth = document.getElementById('four');

var colorChange = function (theID) {
	this.id = theID;
  this.instances.push(this);
  this.formatContent = () => {
  this.revertColors();
  this.id.style.color = "red"
  };
}

colorChange.prototype.instances = [];
colorChange.prototype.revertColors = function() {
  this.instances.forEach(instance => (instance.id.style.color = "black"))
}

test = new colorChange(first);
testAgain = new colorChange(second);
tester = new colorChange(third);
testify = new colorChange(fourth);

function createEventListeners() {
   if (first.addEventListener) {
    first.addEventListener("click", test.formatContent, false);
  } if (second.addEventListener) {
    second.addEventListener("click", testAgain.formatContent, false);
  } if (third.addEventListener) {
    third.addEventListener("click", tester.formatContent, false);
  } if (fourth.addEventListener) {
    fourth.addEventListener("click", testify.formatContent, false);
  }
}

function init(){
	createEventListeners();
}

if (window.addEventListener) {
  //call init() on page load
   console.log("> Adding TC39 Event Listener...");
   window.addEventListener ("load", init, false);
}
else if (window.attachEvent) {
   console.log("> Adding MS Event Listener...");
   window.attachEvent ("onload", init);
}
a {
  text-decoration: none;
  color: black;
}

a:visited {
  text-decoration: none;
	color: black;
}
<html>
<head>
	<title>Test</title>
</head>
<body>
<ul>
	<li><a href="#0" id="one"> Test</a> </li>
	<li><a href="#0" id="two"> Test again</a> </li>
	<li><a href="#0" id="three">Tester </a></li>
	<li><a href="#0" id="four"> Testify</a> </li>
</ul>
</body>
</html>

【讨论】:

  • 我花了很长时间才弄清楚为什么这在示例中有效,但在我的实际项目中却无效。花了一个多小时调试并不断收到关于“this.instances.push(this);”的类型错误。原来我在我的 init 函数中调用了 colorChange 对象。效果很好!谢谢。
【解决方案3】:

有一种更简单的方法可以实现这一点,您不需要 id,您只需要设置一个事件侦听器。

这是一个精简的例子:

// Grab the main ul element and attach a click
// listener to it. This will listen to events that
// bubble up the DOM from other clicked elements
// (event propagation)
const ul = document.querySelector('ul');
ul.addEventListener('click', handleClick, false);

// Grab the list items
const lis = document.querySelectorAll('ul li');

function handleClick(e) {

  // Grab the classList property from the event target
  const { classList } = e.target;

  // Loop over the list items a reset their color
  [...lis].forEach(li => li.classList.remove('active'));

  // add a red class to the clicked element
  classList.add('active');
}
.active { background-color: red; }
<ul class="colors">
  <li>Test</li>
  <li>Test again</li>
  <li>Tester</li>
  <li>Testify</li>
</ul>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 2012-09-22
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 2013-06-16
    相关资源
    最近更新 更多