简体   繁体   English

如何在点击时显示跨度但在单击其他链接时消失?

[英]How can you make a span appear on click but dissapear when another link is clicked?

I am brand new to javascript so please bear with me. 我是javascript的新手,所以请耐心等待。 I am trying to get a span to appear on click which I have accomplished, however I need it to return to being hidden once another link is clicked. 我试图在我已经完成的点击上显示一个跨度,但是我需要它在单击另一个链接后返回隐藏状态。 This is what I have so far. 这就是我到目前为止所拥有的。

<html>
<head>
<style>
aside.apps{
    position:relative;
}

span.socialApp{
    visibility:hidden;
    position:absolute;
    top:20px;
    left: 0;
    background-color:#e9e9e9;
}
</style>

<script>
var state = 'hidden'; 

function showApp(a) { 

    if (state == 'visible') { 
        state = 'hidden'; 
    } 
    else { 
        state = 'visible'; 
    } 

    if (document.getElementById && !document.all) { 
        x = document.getElementById(a); 
        x.style.visibility = state; 
    } 
} 
</script>
</head>

<body>

        <aside class="apps">
            <a href="javascript://" onclick="showApp('app1');">link1</a>
                <span class="socialApp" id="app1">stuff goes here1</span>
            <a href="javascript://" onclick="showApp('app2');">link2</a>
                <span class="socialApp" id="app2">stuff goes here2</span>
            <a href="javascript://" onclick="showApp('app3');">link3</a>
                <span class="socialApp" id="app3">stuff goes here3</span>
            <a href="javascript://" onclick="showApp('app4');">link4</a>
                <span class="socialApp" id="app4">stuff goes here4</span>
        </aside>
</body>
</html>

Currently when link1 is clicked app1 appears, then once link2 is clicked app2 appears over top of link1. 目前,当单击link1时,会出现app1,然后单击link2后,app2将显示在link1的顶部。 When link2 is then closed link1 is still visible. 当link2关闭时,link1仍然可见。 I need to check all 4 and make all hidden except the current selection. 除了当前选择之外,我需要检查所有4并隐藏所有内容。

Slight update; 轻微更新; the function is now self-contained . 该功能现在是独立的

This should work how you want ; 这应该是你想要的 ; it will pull up the correct span, and will hide it again if it is clicked again. 它将拉出正确的跨度,如果再次单击它将再次隐藏它。

Here is the code again: 这是代码:

    <aside class="apps" id="aside">
        <a href="#" onclick="showApp('app1');">link1</a>
            <span class="socialApp" id="app1">stuff goes here1</span>
        <a href="#" onclick="showApp('app2');">link2</a>
            <span class="socialApp" id="app2">stuff goes here2</span>
        <a href="#" onclick="showApp('app3');">link3</a>
            <span class="socialApp" id="app3">stuff goes here3</span>
        <a href="#" onclick="showApp('app4');">link4</a>
            <span class="socialApp" id="app4">stuff goes here4</span>
    </aside>

function showApp(a) {
    var aside = document.getElementById('aside');
    var arr = aside.getElementsByTagName('span');
    for (i = 0; i < arr.length; i++) {
        if (arr[i].getAttribute('id') != a) {
            arr[i].style.visibility = 'hidden';
        }
    }
    var state;
    x = document.getElementById(a);
    if (x.style.visibility == 'visible') {
        state = 'hidden';
    }
    else {
        state = 'visible';
    }
    x.style.visibility = state;
}​

I recommend using JQuery. 我建议使用JQuery。 It has cross browser support and makes simple work of things like this ;). 它具有跨浏览器支持,可以简单地完成这样的工作;)。

include the following in your tags 在您的代码中包含以下内容

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

Here is the new script 这是新脚本

<script type="text/javascript">
    function showApp(a) {
        $(".selected").removeClass("selected");
        $(a).addClass("selected");
    };
</script>  

change your html to this 将你的HTML更改为此

<aside class="apps">
    <a href="#" onclick="showApp('#app1');">link1</a>
        <span class="socialApp" id="app1">stuff goes here1</span>
    <a href="#" onclick="showApp('#app2');">link2</a>
        <span class="socialApp" id="app2">stuff goes here2</span>
    <a href="#" onclick="showApp('#app3');">link3</a>
        <span class="socialApp" id="app3">stuff goes here3</span>
    <a href="#" onclick="showApp('#app4');">link4</a>
        <span class="socialApp" id="app4">stuff goes here4</span>
</aside>

change your css to this 把你的CSS改成这个

.apps{
    position:relative;
}

.socialApp{
    visibility:hidden;
    position:absolute;
    top:20px;
    left: 0;
    background-color:#e9e9e9;
}

.selected {
    visibility: visible;   
}

JSFiddle Example: http://jsfiddle.net/peterf/u2SFL/ JSFiddle示例: http//jsfiddle.net/peterf/u2SFL/

My bad, edited the answer, it would help you. 我的坏,编辑了答案,它会帮助你。 I dont think, there's any need to use a variable. 我不认为,有任何需要使用变量。 Just hide all spans and then show the one you passed as variable. 只需隐藏所有跨度,然后将您传递的变量显示为变量。

<html>
<head>
<style>
aside.apps{
    position:relative;
} 
span.socialApp{
    visibility:hidden;
    position:absolute;
    top:20px;
    left: 0;
    background-color:#e9e9e9;
}
</style>

<script>  
function showApp(a) { 
    var aside = document.getElementById('myaside');
    var spans = aside.getElementsByTagName('span');
    for(i=0,len=spans.length;i<len;i++){
     spans[i].style.visibility = 'hidden';
    }
    x = document.getElementById(a);  
    x.style.visibility = 'visible';  
}

</script>
</head>

<body>

        <aside class="apps" id="myaside">
            <a href="javascript://" onclick="showApp('app1');">link1</a>
                <span class="socialApp" id="app1">stuff goes here1</span>
            <a href="javascript://" onclick="showApp('app2');">link2</a>
                <span class="socialApp" id="app2">stuff goes here2</span>
            <a href="javascript://" onclick="showApp('app3');">link3</a>
                <span class="socialApp" id="app3">stuff goes here3</span>
            <a href="javascript://" onclick="showApp('app4');">link4</a>
                <span class="socialApp" id="app4">stuff goes here4</span>
        </aside>
</body>
</html>

Update: 更新:

As you are new to javascript, just dont dive into jQuery because its easier for someone else and they will throw a code whenever you ask. 因为你是javascript的新手,所以不要深入研究jQuery,因为它对其他人来说更容易,而且只要你问,他们就会抛出代码。

Not me, but all the great javascript developers suggest you to learn javascript before learning its framework. 不是我,但所有优秀的javascript开发人员建议你在学习它的框架之前学习javascript。

Also, jQuery is there to ease things, to simply the code and to separate markup and javascript. 此外,jQuery可用于简化操作,简化代码并分离标记和javascript。

You should not now but if you are willing to try later, you should follow an approach like this. 现在不应该,但如果你愿意稍后再试,你应该遵循这样的方法。 (No onclick in markup and a simpler code) (没有onclick标记和更简单的代码)

<html>
<head>
<style>
aside.apps{
    position:relative;
} 
span.socialApp{
    display:none;
    position:absolute;
    top:20px;
    left: 0;
    background-color:#e9e9e9;
}
</style>
<script src='http://code.jquery.com/jquery-latest.min.js'></script>
<script>
 $(document).ready(function(){
    $('aside').on('click','a',function(){      // This lines says that select aside and fire onclick even on click of anchor tag inside it
        $(this).parent().find('span').hide();    // $(this) is the clicked anchor
        $(this).next('span').show();    // Find the span next to clicked anchor and show it i.e. display:block
    })
 })

</script>
</head> 
<body> 
<aside class="apps">
    <a href="javascript:void(0);">link1</a>
        <span class="socialApp" id="app1">stuff goes here1</span>
    <a href="javascript:void(0);" >link2</a>
        <span class="socialApp" id="app2">stuff goes here2</span>
    <a href="javascript:void(0);" >link3</a>
        <span class="socialApp" id="app3">stuff goes here3</span>
    <a href="javascript:void(0);" >link4</a>
        <span class="socialApp" id="app4">stuff goes here4</span>
</aside> 
</body>
</html>

You should keep track of the currently visible item in a variable (which is initially null ). 您应该跟踪变量中当前可见的项目(最初为null )。

Every time showApp is called, hide the currently visible item. 每次调用showApp ,都会隐藏当前可见的项目。

Then make the span that has just been clicked visible and remember that it is now the currently visible item (unless the one that has just been clicked is the same one that has been visible until now - in that case you shouldn't make anything visible and there no longer is a currently visible item). 然后使刚刚点击的跨度可见,并记住它现在是当前可见的项目(除非刚刚点击的那个是直到现在才可见的那个 - 在这种情况下你不应该看到任何东西并且不再有当前可见的项目)。

and welcome to Stack Overflow! 欢迎来到Stack Overflow!

First off, I am going to suggest you make use of jQuery assist you with your JavaScript. 首先,我建议你使用jQuery帮助你使用JavaScript。 jQuery (and other similar frameworks like Zepto, MooTools and Dojo) irons over some of the cracks in JavaScript such as cross browser inconsistencies and will make things a lot easier . jQuery(以及其他类似的框架,如Zepto,MooTools和Dojo)可以解决JavaScript中的一些问题,例如跨浏览器的不一致性,并且会使事情变得更容易 To include jQuery in your project you just need to add the following in your page's <head> tag: 要在项目中包含jQuery,只需在页面的<head>标记中添加以下内容:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

Now you've got access to jQuery you can remove all of the onclick attributes you added to your <a> tags. 现在您可以访问jQuery,您可以删除添加到<a>标签的所有onclick属性。 The use of onclick tags is discouraged as it dates back to the early days of web development before DOM Level 1 standard was (almost) agreed upon. 不鼓励使用onclick标签,因为它可以追溯到Web开发的早期阶段,之后(几乎)同意DOM级别1标准。 Instead it's suggested you bind to the 'click' event - this will help to keep your HTML and JavaScript separated and in turn make your JavaScript easier to read and debug. 相反,建议您绑定到“click”事件 - 这将有助于保持HTML和JavaScript分离,从而使您的JavaScript更易于阅读和调试。

jQuery makes it really easy to bind a handler (function) to a click event, you just need to use the on syntax: jQuery使得将处理程序(函数)绑定到click事件非常容易,您只需要使用on语法:

// #id is the 'id' attribute of the element you want to add a click handler to.
$('#id').on('click', function () { alert("Clicked!"); }); 

jQuery also provides a quick and easy way to show and hide elements on the page via show and hide , here how it works: jQuery还提供了一种快速简便的方法,通过showhideshowhide页面上的元素,在这里它是如何工作的:

// Again, #id is the id attribute of the element you want to show/hide.
$('#id').show();    // Make a hidden element visible.
$('#id').hide();    // Hide a visible element.

The only thing to watch out for here is that when you 'hide' an element using jQuery it actually sets the display CSS attribute of the element. 这里唯一需要注意的是,当你使用jQuery“隐藏”一个元素时,它实际上设置了元素的display CSS属性。 In your code above, you were hiding elements by toggling the visibility attribute. 在上面的代码中,您通过切换visibility属性来隐藏元素。

The last part of the answer lies in how we the currently visible element; 答案的最后一部分在于我们当前可见元素的方式; this can be achieved by adding a new variable which keeps track of which element is being displayed - you can see this in my modified code below. 这可以通过添加一个新变量来实现,该变量跟踪正在显示的元素 - 您可以在下面的修改后的代码中看到这一点。

<html>
    <head>
        <style>
span.socialApp {
    /* use display: none instead of visibilty: hidden */
    display: none;

    position:absolute;
    top:20px;
    left: 0;
    background-color:#e9e9e9;
}
        </style>

        <!-- include jQuery -->
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

        <!-- Script for toggle apps -->
        <script>
// Create an Array of all the app names.
var apps = [ 'app1', 'app2', 'app3' ];

// Variable which keeps track of which app is currently visible
var visibleAppName = null;

function onLinkClicked(event) {
    // Get the id of the link that was clicked.
    var linkName = event.target.id;

    // Strip off the '-link' from the end of the linkName
    var dashIndex = linkName.indexOf('-link');
    var appName = linkName.substr(0, dashIndex);

    // Call show app with the correct appName.
    showApp(appName);
}

function showApp(appNameToShow) { 
    // Hide the currently visible app (if there is one!)
    if (visibleAppName !== null) {
        $('#' + visibleAppName).hide();
    }

    // And show the one passed
    $('#' + appNameToShow).show();

    // Update the visibleApp property.
    visibleAppName = appNameToShow;
}

// $(document).ready waits for the page to finish rendering
$(document).ready(function () {
    // Walk through the Array of Apps and add a click handler to
    // it's respective link.
    apps.forEach(function(name) {
        $('#' + name + '-link').on('click', onLinkClicked);
    });
});         
        </script>
    </head>
    <body>
            <aside class="apps">
            <a href="#" id="app1-link">link1</a>
            <span class="socialApp" id="app1">stuff goes here1</span>

            <a href="#" id="app2-link">link2</a>
            <span class="socialApp" id="app2">stuff goes here2</span>

            <a href="#" id="app3-link">link2</a>
            <span class="socialApp" id="app3">stuff goes here3</span>            
        </aside>
    </body>
</html>​​​​​​​​​​​

If you're keen to learn more about JavaScript development then may I suggest reading Object Orientation JavaScript which provides an excellent introduction to the language and some of it's quirks. 如果您希望了解有关JavaScript开发的更多信息,那么我是否可以建议阅读面向对象的JavaScript ,它提供了对语言的精彩介绍和一些怪癖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM