JavaScript没有显示隐藏的图片

时间:2016-03-23 19:32:09

标签: javascript html javascript-events

我的JavaScript方法有问题。我只是希望当我点击一个链接时,它会显示隐藏的图片,当我再次点击它时,它会隐藏它,依此类推。但它没有正常工作。这是代码自己检查并尝试帮助我做这件事。最好的祝福。

<head>
<style>
    .hide {
        display: none;
    }
</style>

</head>
<body>


<a data-img='sloth-pic' id='sloth' href='#'>Sloth</a>

<img class='hide' id='sloth-pic' src='https://static-secure.guim.co.uk/sys-images/Education/Pix/pictures/2013/1/17/1358446759827/A-three-toed-tree-sloth-h-008.jpg' style='width:304px;height:228px;'>

 <script>

    var sloth = document.getElementById("sloth");
    var slothPic = document.getElementById("sloth");

    sloth.addEventListener("click", function() {
        if(slothPic.className === "hide") {
            sloth.className = "";
        } else if(sloth.className === ""){
            slothPic.className = "hide";
        }
    });

</script>
</body>

5 个答案:

答案 0 :(得分:0)

试试这个:https://jsfiddle.net/jorge182/cor14ze5/6/

    sloth.addEventListener("click", function() {

            if($('#sloth-pic').hasClass('hide')){

                $('#sloth-pic').removeClass('hide')
            }else{
               $('#sloth-pic').addClass('hide')
            }
        })

答案 1 :(得分:0)

您在JavaScript中使用了错误的AID PRICE 1 20 2 12 3 23 属性。

您可以使用三元运算符进行切换。

试试这个:

id
var sloth = document.getElementById("sloth");
var slothPic = document.getElementById("sloth-pic");
sloth.addEventListener("click", function() {
  slothPic.className = (slothPic.className == "hide") ? "" : "hide";
});
.hide {
  display: none;
}

答案 2 :(得分:0)

我认为你在使用懒惰和懒惰照片时犯了一些错误。它应该是这样的:

ParentComponent implements AfterContentInit{
  @ContentChildren(ChildComponent) contents : QueryList<ChildComponent>; 

  ngAfterContentInit()
  {
     //access contents here
  }

}

你可以在这里找到一个有效的例子:

Autoconfigure classes

答案 3 :(得分:0)

你可以用几行Jquery来做到这一点,参见小提琴https://jsfiddle.net/7oe5kh9L/55/

  $("#sloth").click(function() {
    $(".hide").toggleClass("show")
  });

CSS

.hide {display: none;}

.show {display: inline;}

答案 4 :(得分:0)

如果您打算向图像添加更多类,请使用此代码。

var sloth = document.getElementById("sloth");
var slothPic = document.getElementById("sloth-pic");

sloth.addEventListener("click", function() {
  toggleClass(slothPic, 'hide');
  return false;
});

function toggleClass(element, className){
    if (!element || !className){
        return;
    }

    var classString = element.className, nameIndex = classString.indexOf(className);
    if (nameIndex == -1) {
        classString += ' ' + className;
    }
    else {
        classString = classString.substr(0, nameIndex) + classString.substr(nameIndex+className.length);
    }
    element.className = classString;
}
    .hide {
        display: none;
    }
<a data-img='sloth-pic' id='sloth' href='#'>Sloth</a>

<img class='hide' id='sloth-pic' src='http://www.miamammausalinux.org/wp-content/uploads/2016/03/stackoverflow2.png' style='width:304px;height:228px;'>

相关问题