简体   繁体   English

Javascript根据另一个内容更改div颜色

[英]Javascript to change the div color depending on the content of another

I am creating a calendar for a wordpress site and the events are created using a plugin but I want to be able to dynamically change the background color.我正在为 wordpress 站点创建日历,并且使用插件创建事件,但我希望能够动态更改背景颜色。

I want to modify the event background in the event-background div depending on the text is used in the sub div.我想根据子 div 中使用的文本修改事件背景 div 中的事件背景。 How can I select and modify the style using javascript.如何使用 javascript 选择和修改样式。

<div class="event-background">

    <div class="event-place">South</div>

</div>

The event-place div and text are automatically generated so I can't add anything to the div attribute but the text will always either by North, South, East, West and I would like to apply a different background color for each.事件地点 div 和文本是自动生成的,因此我无法向 div 属性添加任何内容,但文本将始终按北、南、东、西,我想为每个应用不同的背景颜色。

I think it should be possible using If Then Else statements in Javascript but I'm not sure how to implement it.我认为应该可以在 Javascript 中使用 If Then Else 语句,但我不确定如何实现它。

Give the parent div an id such as "event-bg" as seen in the following snippet:为父 div 提供一个 id,例如“event-bg”,如以下代码段所示:

<div id="event-bg" class="event-background">
  <div class="event-place">South</div>
</div>

And then use this code:然后使用此代码:

  var backgroundRef = document.getElementById("event-bg");

  var innerDirectionText = backgroundRef.firstElementChild.innerHTML;

  switch(innerDirectionText) {
    case "North":
      backgroundRef.style.background = "green";
      break;
    case "East":
      backgroundRef.style.background = "yellow";
      break;
    case "South":
      backgroundRef.style.background = "pink";
      break;
    case "West":
      backgroundRef.style.background = "blue";
      break;
    default:
  }

The above code decides what the background colour should be.上面的代码决定了背景颜色应该是什么。 I just used some random background colours.我只是使用了一些随机的背景颜色。

My answer does not cover any error catching or default cases and assumes that your child will always be the first within the parent .我的回答不包括任何错误捕获或默认情况,并假设您的孩子将始终是父级中的第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM