【问题标题】:Do something on :target with javascript使用 javascript 在 :target 上做一些事情
【发布时间】:2010-11-23 11:14:12
【问题描述】:

我正在使用 CSS3 :target 伪选择器来创建页面内导航,而无需重新加载页面。这真的很好用!

但是我有一个问题,当页面定位时,我需要重置页面中的表单,我如何知道元素是否使用 javascript 定位?赞element.ontarget = function();

或者类似element.ondisplaychange -> element.oncsschange

更好的更新:

var hashcache = document.location.hash;
window.onhashchange = function() {
    if(hashcache != document.location.hash) {
        $(hashcache + ' form input').each(function() {
            $(this).val('');
        });
        hashcache = document.location.hash;
    }
}

更新:

$('a[href^="#"]').each(function() {
    this.onclick = function() {
        href = $(this).attr('href');
        if(href != document.location.hash) {
            $(href + ' form input').each(function() {
                $(this).val('');
            });
        }
    }
});

【问题讨论】:

  • onfocusonblur 不起作用

标签: javascript css anchor target


【解决方案1】:

如果您使用 JavaScript 进行导航,我建议您在其中添加检查。但我从你的问题猜测你不是,而是使用带有锚点的普通链接(例如,<a href='#target1'><a href='#target2'>,...)。

几个选项:

使用计时器

在这种情况下,基本上你想做的事情归结为在锚点改变时接收一个事件。据我所知,就在一月份回答this other question on StackOverflow 的人所知,你只能用计时器来做到这一点。 (编辑:但请参阅下面 ide 的评论,有一个新的 hashchange 事件我们很快就能使用!) 例如:

(function() {
    var lastHash = window.location.hash;
    setTimeout(function() {
        var newHash = window.location.hash;
        if (newHash !== lastHash) {
            lastHash = newHash;
            // Trigger your target change stuff
        }
    }, 250);
})();

每季度检查一次更改。这对你来说可能还不够,你可以降低250,但要小心运行过多并减慢其他一切。

但正如你在下面所说的那样,这是低效的。

挂钩链接的click 事件

由于您已经在页面上使用 JavaScript,我建议您改为在链接上使用处理程序。如果你给他们添加一个类名或其他东西(我打赌他们已经有一个;我会在下面给我们“导航链接”),这很容易设置:

var links, index, link;
links = document.getElementsByTagName('a');
for (index = 0; index < links.length; ++index) {
    link = links.item(index);
    if ((" " + link.className + " ").indexOf(" navlink ") >= 0) {
        hookEvent(link, 'click', clickHandler);
    }
}

function clickHandler() {
    // `this` will reference the element that was clicked
}

// The 'hook' function:
var hookEvent = (function() {
    var elm = document.createElement('a');

    function hookEventViaAttach(element, event, handler) {
        element.attachEvent("on" + event, handler);
    }
    function hookEventViaAddListener(element, event, handler) {
        element.addEventListener(event, handler, false);
    }
    function hookEventDOM0(element, event, handler) {
        element["on" + event.toLowerCase()] = handler;
    }

    if (elm.attachEvent) {
        return hookEventViaAttach;
    }
    if (elm.addEventListener) {
        return hookEventViaAddListener;
    }
    // I usually throw a failure here saying not supported, but if you want,
    // you can use the DOM0-style stuff.
    return hookEventDOM0;
})();

如果您使用像 jQueryPrototypeYUIClosureany of several others 这样的库,上述问题的很多复杂性都会消失。

例如,jQuery 版本:

$("a.navlink").click(clickHandler);
function clickHandler() {
    // `this` will reference the element that was clicked
}

原型版本:

$$("a.navlink").invoke('observe', 'click', clickHandler);
function clickHandler() {
    // `this` will reference the element that was clicked
}

【讨论】:

  • 我知道,我以前就是这样做的。但是使用计时器并不是很有效。我正在寻找另一种方法来做到这一点。
  • @Stijntjhe:祝你好运。 :-) 我不认为你会找到一个可靠的、跨浏览器的。您最好将事件处理程序连接到链接。
  • Woot 好主意 :) 没想到 xD
  • @Stijntjhe:大声笑,正如您评论并接受的那样,我正在添加一个示例 FWIW。很高兴有帮助。
  • 这不是手头问题的最佳解决方案,但如果您需要跟踪 URL #fragment 的更改,包括 IE8 在内的所有主要浏览器都支持新的“hashchange”事件.
【解决方案2】:

onfocus 属性返回当前元素上的 onFocus 事件处理程序代码。

event handling code = element.onfocus

onblur 属性返回当前元素上存在的 onBlur 事件处理程序代码(如果有)。

element.onblur = function;

示例:http://jsfiddle.net/g105b/cGHF7/

<html>

<head>
    <title>onblur event example</title>

    <script type="text/javascript">

    var elem = null;

    function initElement()
     {
     elem = document.getElementById("foo");
     // NOTE: doEvent(); or doEvent(param); will NOT work here.
     // Must be a reference to a function name, not a function call.
     elem.onblur = doEvent;
     };

    function doEvent()
     {
     elem.value = 'Bye-Bye';
     alert("onblur Event detected!")
     }
    </script>

    <style type="text/css">
    <!--
    #foo {
    border: solid blue 2px;
    }
    -->
    </style>
</head>

<body onload="initElement()";>
    <form>
    <input type="text" id="foo" value="Hello!" />
    </form>

    <p>Click on the above element to give it focus, then click outside the
    element.<br /> Reload the page from the NavBar.</p>

</body>
</html>

【讨论】:

  • 在我的情况下这不是输入,它是块元素 article 无论如何感谢您的回答。
【解决方案3】:

也许你可以像这样编写代码

function hashChangeEvent(){
    $(window.location.hash)//do something
}
window.onhashchange = hashChangeEvent;//when hash change
hashChangeEvent();//first load

【讨论】:

    猜你喜欢
    • 2013-09-29
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多