2017-03-06 95 views
0

我想在我的main.js頁面放一個包含php的jQuery函數。我能怎麼做 ?把php放在js頁面

<script type="text/javascript"> 

    var r = parseInt('<?php the_field('red'); ?>'); 
    var g = parseInt('<?php the_field('green'); ?>'); 
    var b = parseInt('<?php the_field('blue'); ?>'); 


    $("body").css('background-color', 'rgb(' + r + ',' + g + ',' + b + ')'); 

     var alpha = Math.min($(this).scrollTop()/2000, 1); 
     var r = Math.round((230-parseInt('<?php the_field('red'); ?>')) * alpha + parseInt('<?php the_field('red'); ?>')); 
     /* red : (fin - début + début) */ 
     var g = Math.round((230-parseInt('<?php the_field('green'); ?>')) * alpha + parseInt('<?php the_field('green'); ?>')); 
     /* red : (fin - début + début) */ 
     var b = Math.round((230-parseInt('<?php the_field('blue'); ?>')) * alpha + parseInt('<?php the_field('blue'); ?>')); 

    $(document).scroll(function() { 
     /* red : (fin - début + début) */ 
     $("body").css('background-color', 'rgb(' + r + ',' + g + ',' + b + ')'); 
    }); 

</script> 
+0

你不能把php放在'core js file。(main.js)'上。 –

+0

你會得到什麼錯誤? –

+2

您將無法在JavaScript中執行PHP代碼,因爲這純粹是客戶端,無法在服務器上執行,但您可以使用AJAX或類似的方式調用PHP頁面並返回結果。 – HomerPlata

回答

1

你不能。 PHP在後端由PHP服務器處理,而JS在前端由瀏覽器處理(JS可以在後端也使用NodeJS處理,但這是另一個話題)

現在,完成你所要的試圖做的,在你的頭創建<script>標籤加載main.js,在其中添加一個全局變量之前包含顏色:

<script type="text/javascript"> 
    var _COLORS_ = { 
     r: parseInt('<?php the_field('red'); ?>'), 
     g: parseInt('<?php the_field('green'); ?>'), 
     b: parseInt('<?php the_field('blue'); ?>') 
    }; 
</script> 

然後,在你的main.js文件,讀取該變量:_COLORS.r_COLORS.g_COLORS.b