如何通过Div ID更改Div样式

时间:2018-08-30 23:41:56

标签: javascript html

编辑:根据用户评论,在下面添加了JS。 Here is a great example我要完成的工作:

在一个博客页面上,我想有两个按钮,“音频”(div id =“音频”)和“视频”(div id =“视频”)。

默认情况下,视频将被启用并在div中显示视频播放器。如果用户单击“音频”,则浏览器会将URL的末尾更改为#audio,从而触发div样式更改。这将导致视频播放器被隐藏而音频播放器变得可见。同样,如果用户再次单击视频,则URL的末尾将更改为#video,从而触发div样式更改,并且音频播放器将变为隐藏,视频播放器将变为可见。

大量的研究使我能够打开和关闭单个div,但是我无法弄清楚如何完成上面列出的内容。

这是我的div语句。

URL以#video结尾时

<div id="video" style="position: static; visibility: visible; overflow: visible; display: block;">MY VIDEO PLAYER</div>

<div id="audio" style="position: absolute; visibility: hidden; overflow: hidden; display: block;">MY AUDIO PLAYER</div>

URL以#audio结尾时

<div id="video" style="position: absolute; visibility: hidden; overflow: hidden; display: block;">MY VIDEO PLAYER</div>

<div id="audio" style="position: static; visibility: visible; overflow: visible; display: block;">MY AUDIO PLAYER</div>

我什至不必为此而发布我的JavaScript。它仅可用于打开和关闭单个div。我应该说,我不是编码人员,但是在旅途中遇到了麻烦,这个网站一直是我的首选。第一次问题。

非常感谢这个出色的网站可以提供的任何帮助。

编辑:这是我使用的js,仅允许切换一个div

<script>
function myFunction() {
    var x = document.getElementById("video");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
</script>

3 个答案:

答案 0 :(得分:1)

尽管我目前无法检查,但我首先想到的是使用以下样式表规则:

*,
::before,
::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.wrapper {
  width: 80vw;
  margin: 1em auto;
  border: 1px solid #000;
}

#audio,
#video {
  /* hide both elements by default: */
  visibility: hidden;
}

#audio:target,
#video:target {
  /* show the element whose id is the
         document's hash (‘at the end of
         the URL’) */
  visibility: visible;
}
<nav>
  <ul>
    <li><a href="#video">Video</a></li>
    <li><a href="#audio">Audio</a></li>
  </ul>
</nav>
<div class="wrapper">
  <div id="video">MY VIDEO PLAYER</div>
  <div id="audio">MY AUDIO PLAYER</div>
</div>

JS Fiddle demo

当然,这确实依赖CSS而不是JavaScript;所以这可能不是您想要的答案。

以下是OP留下的评论:

  

不幸的是,我需要默认情况下可以观看视频。然后,如果用户单击音频,视频将被隐藏。

以下代码有效:

/* aesthetics, irrelevant to the actual demo */
*,
::before,
::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.wrapper {
  border: 1px solid #000;
  width: 80vw;
  margin: 1em auto;
}

.wrapper>div {
  flex: 1 0 auto;
  height: 5em;
}


/* using 'display: flex' to allow the use of the
   'order' property on the chilren of this element: */
.wrapper {
  display: flex;
}

/* hiding the child elements of the wrapper by default: */
.wrapper>div {
  visibility: hidden;
}

/* selecting the child of the .wrapper element with
   the class of 'defaultOnLoad', placing it first
   in the visual order of its parent with the
   'order: -1' property; and making it visible on
   page-load: */
.wrapper>.defaultOnLoad {
  order: -1;
  visibility: visible;
}


/* selecting the '.defaultOnLoad' element that
   is a general (later) sibling of an element
   that is the ':target' (whose id appears following
   the '#' in the URL), both of which are children of
   '.wrapper' and hiding that element: */
.wrapper> :target~.defaultOnLoad {
  visibility: hidden;
}

/* finding the child of the '.wrapper' element that
   is the ':target' of the document and making it
   visible: */
.wrapper>:target {
  visibility: visible;
}
<nav>
  <ul>
    <li><a href="#video">Video</a></li>
    <li><a href="#audio">Audio</a></li>
  </ul>
</nav>
<div class="wrapper">
  <!-- in the CSS we'll be selecting/styling the '.defaultOnLoad' element based
       on the state of another sibling being the ':target'; as CSS cannot select
       previous-siblings I've moved the '#video' to be the last child of the
       '.wrapper', but used CSS to maintain the visual order: -->
  <div id="audio">MY AUDIO PLAYER</div>
  <div id="video" class="defaultOnLoad">MY VIDEO PLAYER</div>
</div>

JS Fiddle demo

作为我为什么要推荐CSS而不是JavaScript的演示,当CSS能够执行任务时,请参阅以下内容,其中添加了多个其他媒体选项,而无需更改CSS:

/* aesthetics, irrelevant to the actual demo */
*,
::before,
::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.wrapper {
  border: 1px solid #000;
  width: 80vw;
  margin: 1em auto;
}
.wrapper>div {
  flex: 1 0 auto;
  height: 5em;
}
/* using 'display: flex' to allow the use of the
   'order' property on the chilren of this element: */
.wrapper {
  display: flex;
}
/* hiding the child elements of the wrapper by default: */
.wrapper>div {
  visibility: hidden;
}
/* selecting the child of the .wrapper element with
   the class of 'defaultOnLoad', placing it first
   in the visual order of its parent with the
   'order: -1' property; and making it visible on
   page-load: */
.wrapper>.defaultOnLoad {
  order: -1;
  visibility: visible;
}
/* selecting the '.defaultOnLoad' element that
   is a general (later) sibling of an element
   that is the ':target' (whose id appears following
   the '#' in the URL), both of which are children of
   '.wrapper' and hiding that element: */
.wrapper> :target~.defaultOnLoad {
  visibility: hidden;
}
/* finding the child of the '.wrapper' element that
   is the ':target' of the document and making it
   visible: */
.wrapper>:target {
  visibility: visible;
}
<nav>
  <ul>
    <li><a href="#video">Video</a></li>
    <li><a href="#audio">Audio</a></li>
    <li><a href="#print">Print</a></li>
    <li><a href="#braille">Braille</a></li>
  </ul>
</nav>
<div class="wrapper">
  <!-- in the CSS we'll be selecting/styling the '.defaultOnLoad' element based
       on the state of another sibling being the ':target'; as CSS cannot select
       previous-siblings I've moved the '#video' to be the last child of the
       '.wrapper', but used CSS to maintain the visual order: -->
  <div id="audio">MY AUDIO PLAYER</div>
  <div id="print">The 'print' option</div>
  <div id="braille">The 'braille' option</div>
  <div id="video" class="defaultOnLoad">MY VIDEO PLAYER</div>
</div>

JS Fiddle demo

关于以下来自OP的评论:

  

我遇到的一个问题是ID显然会导致浏览器跳转。是否有一些我不知道的语法会使浏览器保持在原位? …我需要这些DIV元素(音频/视频)中的每一个相互替换,而当用户单击音频或视频时,它们不能跳到另一个或在另一个下面移动。

似乎没有CSS手段可以防止页面滚动到目标元素#video#audio的位置,这可能会阻止使用<a>不幸的是,元素;还有一种替代方法,使用<label><input>元素,但这具有为功能添加额外的HTML元素的复杂性:

/* aesthetics, irrelevant to the actual demo */
*,
::before,
::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
/* giving an arbitrarily large margin-bottom to
   demonstrate that there is no default scrolling
   on clicking the <label>: */
nav {
  margin-bottom: 800px;
}
/* a <label> element doesn't have default styling to imply
   its interactive nature, so here we style the cursor to
   depict that it can be clicked: */
nav label {
  cursor: pointer;
}
.wrapper {
  border: 1px solid #000;
  width: 80vw;
  margin: 1em auto;
}
/* hiding the <div> children contained within the .wrapper
   element: */
.wrapper>div {
  height: 5em;
  visibility: hidden;
}
/* selecting the <div> elements that are the immediate sibling
   of an <input> whose 'type' attribute is equal to 'radio' and
   which matches the ':checked' pseudo-class, and setting their
   visibility to 'visible': */
.wrapper input[type=radio]:checked + div {
  visibility: visible;
}
/* hiding the <input> elements: */
.wrapper input[type=radio] {
  display: none;
}
<nav>
  <ul>
    <!-- using <label> elements instead of <a>; using the 'for'
         (HTMLLabelElement.HTMLFor property) to associate the
         <label> with the relevant <input> (the 'for' attribute
         must be equal to the 'id' attribute/property of the
         <input>: -->
    <li><label for="video">Video</label></li>
    <li><label for="audio">Audio</label></li>
  </ul>
</nav>
<div class="wrapper">
  <!-- we place the <input> as the previous sibling of the relevant
       <div> element (although this is a convenience in order to
       simplify the selector): -->
  <input type="radio" name="mediaChoice" id="video" checked="checked" />
  <div id="video">MY VIDEO PLAYER</div>
  <input type="radio" name="mediaChoice" id="audio" />
  <div id="audio">MY AUDIO PLAYER</div>
</div>

JS Fiddle demo

对上述内容的进一步修订,这次使用JavaScript:

let nav = document.querySelector('nav'),
  mediaContainer = document.querySelector('div.wrapper'),
  // because one option needs to be shown on page-load, and
  // the user's ability to choose the media is determined
  // via the click event, here we have to create a click
  // event (a new MouseEvent), which can bubble through
  // the DOM to be detected by an ancestor:
  clickEvent = new MouseEvent('click', {
    'bubbles': true
  });

// named function to handle events; the EventObject
// ('event') is passed automagically from the 
// EventTarget.addEventListener() method:
function mediaToggle(event) {

  // preventing the default behaviour of the
  // HTMLAnchorElement (which prevents the link
  // being 'followed' and prevents page-jumping):
  event.preventDefault();

  // here we retrieve the hash (the '#identifier'
  // fragment) of the clicked (event.target) <a>
  // element:
  let selector = event.target.hash;
  
  // here we retrieve the NodeList of all '.media'
  // elements in the document; and use
  // NodeList.forEach() to iterate over that collection:
  document.querySelectorAll('.media').forEach(
  
    // we're using an Arrow function here; 'elem' is a
    // reference to the current element-node of the NodeList
    // over which we're iterating:
    (elem) => {
    
      // here we perform this function for all nodes;
      // using the Element.classList API  to toggle the
      // 'active' class; the switch which follows determines
      // whether the class-name is added, retained, removed or
      // or left off. The 'switch' is a condition which evaluates
      // to a true/false (or truthy/falsey) result:
      elem.classList.toggle('active',
        // here we use Element.matches(CSSSelector) to test whether
        // the current element-node matches the supplied CSS selector;
        // if it does the class-name is added (or retained), if not
        // the class-name is removed (or not-added):
        elem.matches(selector));
    });
}

// adding the mediaToggle() function - note the deliberate lack of
// parentheses - as the event-handler for the 'click' event:
nav.addEventListener('click', mediaToggle);

// using Element.querySelector() to find the first/only element
// that matches the supplied CSS selector
nav.querySelector('.defaultOnLoad')
  // firing the created MouseEvent on that element via
  // the EventTarget.dispatchEvent() method:
  .dispatchEvent(clickEvent);
*,
::before,
::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.wrapper {
  border: 1px solid #000;
  width: 80vw;
  margin: 1em auto;
}

.media {
  visibility: hidden;
}

.media.active {
  visibility: visible;
}
<nav>
  <ul>
    <!-- using the 'defaultOnLoad' class-name to identify which media
         should be the default on page-load: -->
    <li><a href="#video" class="defaultOnLoad">Video</a></li>
    <li><a href="#audio">Audio</a></li>
    <li><a href="#print">Print</a></li>
    <li><a href="#braille">Braille</a></li>
  </ul>
</nav>
<div class="wrapper">
  <div id="video" class="media">Video</div>
  <div id="audio" class="media">Audio</div>
  <div id="print" class="media">Print</div>
  <div id="braille" class="media">Braille</div>
</div>

JS Fiddle demo

参考文献:

答案 1 :(得分:0)

这是一种简单的js方法。我在这里做出一些假设(关于您的标记)。

function doMagic() {

    let urlType = window.location.href,
        audio =  document.getElementById('audio'),
        video =  document.getElementById('video');

    if (urlType.split('#')[1] === 'audio'{ //turn it into an array of two, split at the hash
        audio.style.display = 'block';
        video.style.display = 'none';
    }

    if (urlType.split('#')[1] === 'video'{
        audio.style.display = 'none';
        video.style.display = 'block';
    }

}

// assuming you have a button element for this

let videoBtn = document.getElementById('vidBtn'),
    audBtn = document.getElementById('audBtn');

vidBtn.addEventListener('click', function() { doMagic(); }); 
audBtn.addEventListener('click', function() { doMagic(); });

两个事件侦听器都调用相同的函数。如果您的按钮具有相同的类,则可以将其简化为一个事件侦听器。

// assuming your buttons have the class name "myBtn"
let theBtn = document.getElementByClass('myBtn');

theBtn.addEventListener('click', function() { doMagic(); }); 

答案 2 :(得分:0)

我找到的答案不是用普通的javascript完成的,而是用称为jquery的框架完成的。您可以从他们的websitew3schools了解更多有关jquery的信息。 下面是代码。

$("#audio").click(function(){
		$("#audio").toggleClass("active");
		$("#video").toggleClass("active");

	});
	$("#video").click(function(){
		$("#video").toggleClass("active");
		$("#audio").toggleClass("active");
	});
.active{
			background-color: blue;
		}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<div id="video" class = "active" style="position: static; visibility: visible; overflow: visible; display: block;">MY VIDEO PLAYER</div>
<br>
<div id="audio" style="position: static; overflow: hidden; display: block;">MY AUDIO PLAYER</div>

首先,我们检查何时单击具有ID音频的元素,然后在视频ID和音频ID的有效和无效类别之间进行切换。 同样,当我们检查要点击的ID视频时,会在视频ID和音频ID之间切换活动类别。 希望对您有所帮助:)