【问题标题】:i want to define the location of the hyperlink href "#"我想定义超链接href“#”的位置
【发布时间】:2018-03-09 13:26:48
【问题描述】:

我要定义超链接href "#"的默认位置

 <div class="main" id="#a">
        <div class="child"> <a href="#">click</a>
        </div>
 </div>

我想要一种情况,如果用户点击一个 URL,例如:

<a href="#">click</a>

他被重定向到带有id="#a" 的div 类。我希望该 div 类成为页面的默认顶部,而不是将用户带到页面的最顶部。

【问题讨论】:

    标签: html css hyperlink attributes tags


    【解决方案1】:

    所以您想更改以下默认行为:

    <a href="#">click</a>
    

    所以它会将你带到你的“主要”div:&lt;div class="main"&gt;content&lt;/div&gt;

    您可以使用 javascript 和 jQuery 编写一个函数来使用 href="#" 识别页面上的锚元素,并告诉它们执行您想要的行为而不是默认行为,如下所示:

    // select a elements with href="#" and add event listener on click
    $( 'a[href="#"]' ).on( 'click', function( e ){
    
        // prevent default behaviour of jumping to the top of the page
        e.preventDefault();
    
        // get target element position in pixels
        target = $( $( 'div.main' ) ).position().top;
    
        // animate a scroll effect to the pixel location
        $('html,body').stop().animate({ scrollTop: target });
    } );
    

    【讨论】:

    • 问题是问如何将# 的含义从“页面顶部”更改为“id 为#a 的div”。它不是询问如何在 # 之后键入 id。
    • 谢谢@Quentin,你真正理解我的问题.....我想更改默认位置 a href="#">click 指向带有类的 div 元素“主要”
    • @Frish 我尝试了你的解决方案..我在控制台中得到了这个 ------ jquery-3.2.1.min.js:2 Uncaught Error: Syntax error, unrecognized expression: a[ href=#]
    • @ebukaloper 哎呀,看起来 css attribute selector 需要引号作为值。我已经在我的回答中解决了这个问题。
    • 可能是同一个人给你的!也可能是因为问题上没有 javascript/jquery 标签,而我提供了 javascript/jquery 答案。无论如何我很高兴它对你有用:)
    【解决方案2】:

    你可以试试

    <a href="#a">click</a>
    

    【讨论】:

    • 我明白这一点......但我想更改 click 的默认位置以指向类为“main”的 div 元素
    猜你喜欢
    • 1970-01-01
    • 2011-03-07
    • 2011-10-13
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    相关资源
    最近更新 更多