2016-04-29 3 views
0

から読み込んでください。私はCSSスタイルからJavascriptから変数を読み込み、それに応じてCSSの "top"値を設定したいと思います。例:JavascriptからPHP変数を設定して、<style>を

$topPosition = false; 
?> 
<script language='JavaScript' type='text/javascript'> 
    function windowsHeightPixels() { 
     windowsHeight = $(window).height() 
     if (windowsHeight > 750) { 
      topPosition = false; 
      //set the $topPosition = false; 
     } 
     else { 
      topPosition = true; 
      //set the $topPosition = true;    
     } 
    } 
    windowsHeightPixels(); 
    alert ("Height is " + windowsHeight + " Top Position is " + topPosition); 
</script> 

<style> 
... 
#fixedbutton { 
    position: fixed; 
    <?php if ($topPosition === false) : ?> top: 650px; 
    <?php else : ?> top: 127px;</p> 
    <?php endif; ?> 
    ... 
} 
</style> 
+0

このリンクhttp://stackoverflow.com/questions/5338972/how-to-include-php-code-in-見てみてcss – theinarasu

答えて

1

編集:ページの読み込み時にウィンドウの高さを確認するためにリファクタリングされます。

ここでは、少し異なるアプローチを考えてみたいです。 PHP変数は必要ありません。あなたが提供したサンプルコードで判断すると、私はあなたがjQueryを使用していると仮定しています。

あなたのCSSのためにその後
<script> 
    function windowHeightThreshold() { 
     var heightThreshold = 750; 
     return $(window).height() > heightThreshold; 
    } 
    function checkWindowHeight() { 
     var targetElement = $('#fixedbutton'); 
     if (windowHeightThreshold()) { 
      targetElement.addClass("windowHeightThreshold"); 
     } else { 
      targetElement.removeClass("windowHeightThreshold"); 
     } 
    } 

    $(window).on("resize", function() { 
     checkWindowHeight(); 
    });   
    $(document).ready(function() { 
     checkWindowHeight(); 
    }); 
</script> 

、:

<style> 
    #fixedbutton { 
     position: fixed; 
     top: 127px; 
    } 
    #fixedbutton.windowHeightThreshold { 
     top: 650px; 
    } 
</style> 
+0

あなたの答えをありがとう - それは非常に近いです。ページをズームすると、正しい位置に置かれます。ズーム> 149%で固定ボタンを移動します。ページを更新すると、ズームレベルに関係なく常に同じ位置にリセットされます。 –

+0

今すぐうまくいきます。ありがとうございました。 –