【发布时间】:2023-03-03 03:45:01
【问题描述】:
我想根据屏幕大小替换文本 (max-width:700px)。我想用 JavaScript 代替,if/else 代替屏幕尺寸。
这是我的代码:
.membre5 {
display: inline-block;
position: relative;
top: 15px;
margin: 0 auto;
justify-content: space-between;
max-width: 50vw;
box-sizing: border-box;
align-items: center;
text-align: center;
/* transform: translateX(50%); */
padding-bottom: 150px;
}
.card {
margin-left: auto;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.3);
max-width: 300px;
max-height: 540px;
text-align: center;
background-color: grey;
}
img.skin {
max-width: 300px;
max-height: auto;
}
.title {
color: rgb(210, 210, 210);
font-size: 18px;
}
.nom {
font-size: 2.5vw;
color: inherit;
color: white;
}
button {
border: none;
outline: 0;
display: inline-block;
padding: 8px;
color: white;
background-color: #000;
text-align: center;
cursor: pointer;
width: 100%;
font-size: 18px;
}
a {
text-decoration: none;
}
button:hover,
a:hover {
opacity: 0.7;
}
.card {
font-family: odin rounded;
font-size: 120%;
}
<div class="membre5">
<div class="card">
<img class="skin" src="https://cdn1.imggmi.com/uploads/2018/7/19/82b5f414cf833e05e6dd86cef344a52f-full.png" alt="ALLiAnce" style="width:100%">
<h1 class="nom">ALLiAnce</h1>
<p class="title" id="comp">Admin et remplaçant</p>
<script>
function myFunction(x) {
if (x.matches) { // If media query matches
function test() {
var str = document.getElementById("comp").innerHTML;
var res = str.replace("Admin et remplaçant", "Membre");
document.getElementById("comp").innerHTML = res;
}
}
}
var x = window.matchMedia("(max-width: 700px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes
</script>
<p><button>Contact</button></p>
</div>
</div>
所以我想改的文字:"Admin et remplaçant"改成"Membre",但是脚本不行,不知道为什么(我从很多网站上拿了脚本,放在一体)。麻烦您说一下有什么问题吗?
谢谢。
【问题讨论】:
-
您是否收到任何错误或只是不是预期的输出?
-
我没有任何错误。
-
我认为你没有运行
test()。if (x.matches) {的计算结果为true,您定义了一个函数test(),其中仅发生未运行的替换。 -
这是因为关闭。你永远不会调用
test()它是一个嵌套函数。
标签: javascript html css replace responsive