在同一个div上多次单击时还原更改

时间:2017-08-18 09:28:57

标签: javascript css reactjs

我有一个div映射,因此它会根据数据库发送的数据呈现任意次数。我点击div时在div中设置背景颜色。如果再次单击div,我该如何还原更改?

我的代码

handleClick(id) {

let el = document.getElementById(id);

        if (el) {

            el.style.backgroundColor = "#0b97c4";
            el.style.color = "#FFFFFF";

            this.setState({

                voteCount: this.state.voteCount + 1

            })
        }

        this.props.submitvote(vote_object)

}

render() {

        let {contents, submitvote, postId, voted_id} = this.props

        return (

            <div className="txt_vote_bar_div" id={this.props.contents.post_poll_content_id}>
                <p className="txt_vote_choice" id={this.props.contents.post_poll_content_id}
                onClick={() => {this.handleClick(this.props.contents.post_poll_content_id);}}>
                    {contents.content}
                </p>
                <p className="txt_tot_votes"> {this.props.contents.votes_percentage}%
                ({this.state.voteCount} Votes)
                </p>
            </div>
        );
    };

使用上面的代码我成功地改变了div的背景。如果我再次选择相同的div(删除背景颜色或将其更改为其他颜色),如何删除背景颜色

2 个答案:

答案 0 :(得分:0)

我会txt_vote_choice&#34; old&#34; CSS名称,txt_vote_clicked是您要更改的新className。通过onClick,在这两个类之间切换className就可以了。

&#13;
&#13;
handleClick(id) {
  let el = document.getElementById(id);
  if (el) {
    if el.class == "txt_vote_choice" ? "txt_vote_clicked": "txt_vote_choice";

    this.setState({
      voteCount: this.state.voteCount + 1
    })
  }

  this.props.submitvote(vote_object)
}

render() {

  let {contents, submitvote, postId, voted_id, voted_css} = this.props

  return (
    <div  className="txt_vote_bar_div"
          id={this.props.contents.post_poll_content_id}>
      <p  className={voted_css}
          id={this.props.contents.post_poll_content_id}
          onClick={() => {this.handleClick(this.props.contents.post_poll_content_id);}}>
        {contents.content}
      </p>
      <p className="txt_tot_votes"> 
        {this.props.contents.votes_percentage}%({this.state.voteCount} Votes)
      </p>
    </div>
  );
};
&#13;
&#13;
&#13;

然后相应地更新CSS

答案 1 :(得分:0)

如果它只是一个“开 - 关”功能,你可以检查你的div上已经存在的“活动”样式:if (el.style.backgroundColor == "#0b97c4";) //if the style is already there:然后你运行一些代码,让你的div正确的颜色

if (el)
{
    if (el.style.backgroundColor == "#0b97c4";) //if the style is already there:
    {
        el.style.backgroundColor = "#FF0000";
        el.style.color = "#000000"; //put theese 2 colors to the "unactivated" ones

        //other code when you unselect goes here like this.state.voteCount - 1
    }
    else
    {
        el.style.backgroundColor = "#0b97c4";
        el.style.color = "#FFFFFF";

        this.setState({
            voteCount: this.state.voteCount + 1
        })
    }
}