2016-12-20 18 views
-3

我有5-10環節都具有相同的類/A HREF類滾動到div的

<a class="content-link" href="/profile/about-me/<? echo $row['username'];?>/"> 

當此鏈接,用戶點擊次數,則用戶然後我試圖做到的,是導航到使用javascript的#profile-body div。

與此非常相似post但是,唯一的區別是,我不希望用戶導航到像這樣的href的div,而是我需要它通過JavaScript來完成,以便我有鏈接在href實際上加載。

Thankyou提前爲您提供任何幫助。

+0

@Pete帶你的地方在當前頁面,而不是擔心剛剛加載的輪廓主體專區內的鏈接,多數民衆贊成:) –

+0

@Pete鏈路負載和用戶被帶到該部分:) –

+1

@LewisDay這只是矛盾你以前的評論。 –

回答

3

我知道你正在尋找一個Javascript解決方案,但以防萬一你願意使用jquery這裏是一個好的。

$(document).ready(function() { 
    $('.content-link').click(function(e) { 
    e.preventDefault(); 

    $('html, body').animate({ 
     scrollTop: $('#profile-body').offset().top 
    }, 500); 
    }); 
}); 
+1

Ooops我忘記了事件監聽器,編輯我的答案。 –

+0

謝謝!不知道這可以很容易地實現這個謝謝你。將很快標記爲答案 –

+0

但是使用e.preventDefault()實際上會阻止加載新的URL。 – Roberrrt

1

沒有理由使用jQuery雖然(除非你已經在使用它),這是一個充滿香草的方法。設置散列是可選的。

基本上,這個腳本包含在新的頁面中,你手動設置了散列,然後切換offsetTop。

(function() { 
 
    window.location.hash = "three"; 
 
    document.getElementById('three').offsetTop + "px"; 
 
})();
div { 
 
    height: 250px; 
 
    margin-bottom: 10px; 
 
    background-color: #F00; 
 
}
<div id='one'>one</div> 
 
<div id='two'>two</div> 
 
<div id='three'>three</div>

0

這樣做的簡單的方法是通過JQuery:

$(".content-link").click(function() { 
    $('html,body').animate({ scrollTop: $(this.hash).offset().top }, 400); 
}); 

有了這個,你把所有的.content.link HREF控制。

無論如何,這是值得看一看flesler/jquery.scrollTo

0

這也可以做CSS

body { 
 
    background: #999 
 
} 
 
.mylinks a { 
 
    text-decoration: none; 
 
    color: black; 
 
    display: inline-block; 
 
    padding: 2%; 
 
    background: #444; 
 
    color: #999; 
 
} 
 
.mycooldiv { 
 
    background: red; 
 
    width: 100%; 
 
    height: 400px; 
 
    margin-bottom: 30%; 
 
    box-shadow: inset 0 0 10px 200px rgba(0, 0, 0, 0.55); 
 
} 
 
#profile-section1 { 
 
    background: red; 
 
    bottom: 100% 
 
} 
 
#profile-section2 { 
 
    background: blue; 
 
    bottom: 200% 
 
} 
 
#profile-section3 { 
 
    background: green; 
 
    bottom: 300% 
 
} 
 
#profile-section4 { 
 
    background: yellow; 
 
    bottom: 400% 
 
}
<body> 
 
    <div class="mylinks"> 
 
    <a class="content-link" href="#profile-section1">section 1 </a> 
 
    <a class="content-link" href="#profile-section2">section 2 </a> 
 
    <a class="content-link" href="#profile-section3">section 3 </a> 
 
    <a class="content-link" href="#profile-section4">section 4 </a> 
 
    </div> 
 
    <div class="mycooldiv" id="profile-section1"></div> 
 
    <div class="mycooldiv" id="profile-section2"></div> 
 
    <div class="mycooldiv" id="profile-section3"></div> 
 
    <div class="mycooldiv" id="profile-section4"></div> 
 
</body>