如何仅使用 Javascript 附加内容

问题描述

我在下面的 jQuery 中得到了这个,在窗口宽度小于 1024px 的地方,我想附加“.moveThisContent”并将其移动到“.newLocation”在 Javascript 中执行此操作的最佳方法是什么?是否会使用 .appendChild

if($(window).width() < 1024){
  $(".newLocation").append($(".moveThisContent"));
}

解决方法

您可以使用 both,对于设置和获取内容,您可以使用 getElementsByClassName

innerHTML
const width  = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if( width < 1024 ){
    document.getElementsByClassName('newLocation')[0].innerHTML = document.getElementsByClassName('moveThisContent')[0].innerHTML;
    document.getElementsByClassName('moveThisContent')[0].innerHTML = '';
}
.moveThisContent{color:blue;}
.newLocation{color:red;}

,

有了这个,我使用了 .appendChild 并且可以满足我的需求。

,

这是你想做的事情

你可以参考这个链接Here

您可以在 javascript 中使用媒体查询来检查窗口宽度

if (window.matchMedia("(max-width: 1024px)").matches) {
  /* The viewport is less than,or equal to,1024 pixels wide */
  var element = document.getElementByClassName("newLocation");
  element.classList.add("moveThisContent");
} else {
  /* The viewport is greater than 1024 pixels wide */
}

,

稍微扩展一下这个答案 https://stackoverflow.com/a/66886186/3825777,我想我会尝试让视觉学习者在视觉上清晰。我还想弄清楚我们在谈论什么宽度。请看控制台,看看你认为你说的宽度是小于还是大于1024。

$('#sWidth').text(window.screen.width);
$('#sHeight').text(window.screen.height);
$('#wWidth').text($(window).width());
$('#wHeight').text($(window).height());


const width  = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
console.log(width);
if( width < 1024 ){
    document.getElementsByClassName('newLocation')[0].innerHTML = document.getElementsByClassName('moveThisContent')[0].innerHTML;
    document.getElementsByClassName('moveThisContent')[0].innerHTML = '';
}
.moveThisContent{color:#111111;}
.newLocation{color:#777777;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Screen width: <span id="sWidth"></span><br>
Screen height: <span id="sHeight"></span><br>
Window width: <span id="wWidth"></span><br>
Window height: <span id="wHeight"></span><br>



<div class="moveThisContent"> This inner html content is inside a div with class name moveThisContent and in the css this has the color #111111.  I chose the number one not because I like the color 111111,but because I wanted to make it known that his is the first div in the HTML. The content of this div which is the text that you are reading should only move to the div with class name newLocation if the width of your screen is less than 1024 pixels.  The color of this other div is #777777. You will know the content moved if the text you are reading is grey.</div>
<div class="newLocation">The class name of this div is newLocation and the CSS hexidecimal color code for this div is 777777.  The content of this div will change to the content of the div before it if your screen width is less than 1024 pixels  </div>