简体   繁体   English

使用javascript_tag更改Rails中的页面背景颜色

[英]Using javascript_tag to change page background color in rails

I'm creating an application to track player characters. 我正在创建一个用于跟踪玩家角色的应用程序。 I thought it would be cool to have the character's page's background change depending on the current percentage of its maximum health. 我认为根据当前角色最大健康状况的百分比来更改角色页面的背景会很酷。 I'm trying to use the 'javascript_tag' tag to change it dynamically. 我正在尝试使用'javascript_tag'标签进行动态更改。

Here is the code snippet from the show_html_erb file: 这是show_html_erb文件的代码片段:

<% javascript_tag do %>
    var perc = @character.getPercentHealth.to_json %>";
    if (perc > .5) {
        document.body.style.backgroundColor = "green";
    }else if(perc > .25) {
        document.body.style.backgroundColor = "yellow";
    }else if(perc > 0){
        document.body.style.backgroundColor = "red";
    }else{
        document.body.style.backgroundColor = "grey";
    }
<% end %>

For additional reference, here is the getPercentHealth method from my character.rb file: 作为其他参考,这是我character.rb文件中的getPercentHealth方法:

def getPercentHealth
    perc = 0.00
    perc = hitpoints / maxHP
    return perc
end

It runs smoothly, but does not change the background color. Any suggestions?

You don't need to use JavaScript for that unless you want to? 除非您需要,否则不需要使用JavaScript? You can just do: 您可以这样做:

<% if @character.getPercentHeath > 5 %>
<body style="background-color: red;">
<% end %>

The above solution is nice in that it uses css only. 上面的解决方案很好,因为它仅使用css。 However, ideally, css is separated from html and as much as possible logic is abstracted from view files. 但是,理想情况下,css与html是分开的,并且尽可能多地从视图文件中提取逻辑。 To make this cleaner, I would be inclined to create a helper method which is passed the percentage health variable and returns a className eg 为了使这个更清洁,我倾向于创建一个帮助器方法,该方法将传递百分比健康状况变量并返回一个className例如

helper_file.rb helper_file.rb

def health(percentage)
  case percentage
    when > 0.5
      "goodHealth"
    when > 0.25
      "mediocreHealth"
    when > 0
      "poorHealth"
    else
      ""
  end 
end

view.erb 视图

<body class="<%=health(percentage) %>">

styles.css styles.css

.illHealth {background-color: red;}
.mediocreHealth {background-color: yellow;}
.goodHealth {background-color: green;}
.noHealth {background-color: grey;}

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

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