使用 javascript 在 :target 上做一些事情

发布于 2024-10-04 03:05:23 字数 924 浏览 2 评论 0 原文

我使用 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('');
            });
        }
    }
});

I'm using the CSS3 :target pseudo selector to create in-page navigation without reloading the page. This works really well!

But I have a problem, I need to reset the forms in a page when the page targetted, how can I know if an element is targetted with javascript? Like element.ontarget = function();

Or maybe something like element.ondisplaychange -> element.oncsschange?

BETTER UPDATE:

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

UPDATE:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

仙气飘飘 2024-10-11 03:05:23

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

几个选项:

使用计时器

在这种情况下,基本上您想要做的事情可以归结为在锚点更改时接收事件。据我所知,以及回答 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,因此我建议您在链接上使用处理程序。如果你向它们添加一个类名或其他东西(我打赌他们已经有一个;我将在下面使用“navlink”),这很容易设置:

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;
})();

如果你使用像这样的库,上面的很多复杂性都会消失jQuery原型YUI关闭,或其他任何一个

例如,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
}

If you're using JavaScript for the navigation, I'd suggest just adding the check to that. But I'm guessing from your question you're not, that you're instead using plain links with just anchors (e.g., <a href='#target1'>, <a href='#target2'>, ...).

A couple of options:

Use a Timer

In that case, basically what you want to do boils down to receiving an event when the anchor changes. As far as I know, and as far as the people answering this other question on StackOverflow in January knew, you can only do that with a timer. (Edit: But see ide's comment below, there's a new hashchange event we'll be able to use soon!) E.g.:

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

That checks for changes every quarter second. That may not be enough for you, you could lower the 250, but beware running too much and slowing everything else down.

But as you say below, this is inefficient.

Hook the Link's click event

Since you're already using JavaScript on the page, I'd recommend using handlers on your links instead. If you add a class name or something to them (I bet they already have one; I'll us "navlink" below), this is easily set up:

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;
})();

A lot of the complication of the above goes away if you use a library like jQuery, Prototype, YUI, Closure, or any of several others.

For instance, the jQuery version:

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

The Prototype version:

$("a.navlink").invoke('observe', 'click', clickHandler);
function clickHandler() {
    // `this` will reference the element that was clicked
}
属性 2024-10-11 03:05:23

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>

The onfocus property returns the onFocus event handler code on the current element.

event handling code = element.onfocus

The onblur property returns the onBlur event handler code, if any, that exists on the current element.

element.onblur = function;

Example: 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>
霞映澄塘 2024-10-11 03:05:23

也许你可以像这样编码

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

Maybe youcan just code like this

function hashChangeEvent(){
    $(window.location.hash)//do something
}
window.onhashchange = hashChangeEvent;//when hash change
hashChangeEvent();//first load
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文