簡體   English   中英

如何使用JavaScript或PHP在運行時更改HTML元素的CSS屬性?

[英]How I can change the CSS properties of HTML elements in run time using JavaScript or PHP?

我開發了一個包含php頁面的PHP網站。 這些網頁具有頁眉和頁腳分區。 我將Header和Footer分區放在單獨的php文件中,然后使用php include函數將它們include

問題是我有鏈接到標題和頁腳php文件中的主菜單。

在使用include函數之前,我使用了link標簽的CSS Class屬性以不同的格式顯示當前選擇的鏈接。

<a id="Link_Home" class="current">Home</a>
<a id="Link_AboutUs" >About Us</a>
<a id="Link_Branches" >Branches</a>
<a id="Link_Services" >Services</a>
<a id="Link_ContactUs" >Contact Us</a>

使用include函數后如何才能這樣做?

我應該使用JavaScript將鏈接的ID或名稱傳遞給具有該特定格式和樣式的當前鏈接嗎? 如果是這樣,我該怎么做?

有沒有辦法直接使用PHP來更改HTML元素的CSS屬性,以便我可以在運行時修改類屬性? 我怎樣才能做到這一點?

我非常感謝您的幫助和感謝。

如果在php中你可以在類似的條件下寫class="current"

<a id="Link_Home" <?php if($page == 'home'){echo 'class="current"';} ?> >Home</a>

您可以使用ajax加載頁面。 我是說把你的頁面分成3部分。 #header,#content和#footer。 您可以使用jQuery庫添加它:

//adding code to all a tags to manually deal links
$("#footer a").click( function(e){
    // check if this has class "current"
    if($(this).hasClass("current")){

    }else{
    //remove all class "current" and add one
    $('#footer a').removeClass("current");
    //add class "current" to the selected one
    $(this).addClass("current");
    //get location of the target link
        var url = $(this).attr("href");
        //prevent broswer default behavior, e.g. opening the link in a new window
        e.preventDefault();
       //load html from the given address to #content
       loadPage(url);
       }
});

function loadPage(url) {
    //adding a loading icon
    $('#content').html('<div id="progress"><img src="images/ajax-loader.gif" /></div>');
//when completed, remove the icon
    $('#content').load(url, function(){
        $('#progress').remove();
    });
}

這只是一個解決方案。 它可以幫助您更新頁面內容而無需刷新,因此您的所有JavaScript數據都保持不變。 Ajax使您的網站更快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM