Javascript If / else样式更改

时间:2015-10-31 01:26:16

标签: javascript css if-statement onclick

我有一个简单的if else语句的问题,它会根据当前颜色更改<p>元素的文本颜色。我明白为什么我会得到一定的结果,但我似乎无法找到解决方案。对我这样的新手有任何帮助表示赞赏。

HTML

<p id="demo">JavaScript can change the style of an HTML element.</p>

JS TRY 1

<script> 
var x = document.getElementById("demo");

    function one() {  

x.style.fontSize="16px";
x.style.color="black";}

function two() {

x.style.fontSize="16px";
x.style.color="red";}

function three(){

if(x.style.color="black") { two() }
else {one()
}
}
</script>` <button type="button" onclick="three()">Click Me!</button>

JS TRY 2

<script> 
var brojilo = 1 ;
function three(){ 
 var x = document.getElementById("demo");

function two() {

x.style.fontSize="18px";
x.style.color="red";}

function one() {  

x.style.fontSize="18px";
x.style.color="black";}

if (brojilo % 2 == 0)
{one()} 
else
{two()}

var brojilo = brojilo + 1 ;

}
</script><button type="button" onclick="three()">Click Me!</button>

JS TRY 3

<script> 
var b2 = 0 ;

function brojanje(){
var b2 = b2+1;}

function three(){ 
 var x = document.getElementById("demo");

function two() {

x.style.fontSize="18px";
x.style.color="red";}

vfunction one() {  

x.style.fontSize="18px";
x.style.color="black";}

if (b2 % 2 == 0)
{one()} 
else
{two()}
}
</script><button type="button" onclick="three(); brojanje ();">Click Me!</button>

3 个答案:

答案 0 :(得分:2)

您可以使用getComputedStyle获取元素的颜色。

  

window.getComputedStyle(x,null).color

由于您的演示版的color属性的值为&#39;元素尚未初始化,它包含默认值rgb(0,0,0),它对应于黑色。

请参阅下文,了解两种颜色之间的切换示例:

&#13;
&#13;
// use app\components\MyHelpers; // For Yii2 Basic (app folder won't actually exist)
&#13;
MyHelpers::hello("John");
&#13;
&#13;
&#13;

答案 1 :(得分:1)

你可以使用变量来缓存当前颜色,例如:

(function(){
  var color = 'red';

  var demoEl = document.getElementById("demo");
  demoEl.addEventListener('click', function(e) {
      if (color === 'red') {
          demoEl.style.color = 'black';
          color = 'black';    // set current color
      } else {
          demoEl.style.color = 'red';
          color = 'red';
      }
  }, false);
})();

<p id="demo">JavaScript can change the style of an HTML element.</p>

答案 2 :(得分:0)

使用getComputedStylefunction findPayment() { /* Add User's unique input fields here */ var regPrice = document.getElementById("rPrice").value; deposit = document.getElementById("deposit").value; rate = document.getElementById("iRate").value; mth = document.getElementById("tMonth").value; /* Find updated price including user's deposit */ uptPrice = regPrice - deposit; /* Formula to Calculate Here */ topHalf = uptPrice * ( rate / mth ); bottomHalf = 1 - Math.pow( 1 + rate / 12, -mth) custom = topHalf / bottomHalf; /* Send monthly payment to console so I can check */ console.log(custom); }; 用于内联CSS。