繁体   English   中英

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

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

我正在创建一个用于跟踪玩家角色的应用程序。 我认为根据当前角色最大健康状况的百分比来更改角色页面的背景会很酷。 我正在尝试使用'javascript_tag'标签进行动态更改。

这是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 %>

作为其他参考,这是我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?

除非您需要,否则不需要使用JavaScript? 您可以这样做:

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

上面的解决方案很好,因为它仅使用css。 但是,理想情况下,css与html是分开的,并且尽可能多地从视图文件中提取逻辑。 为了使这个更清洁,我倾向于创建一个帮助器方法,该方法将传递百分比健康状况变量并返回一个className例如

helper_file.rb

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

视图

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

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