添加图元跨度而不更改现有居中图元的位置

  • 本文关键字:图元 位置 添加 html css center
  • 更新时间 :
  • 英文 :


这是我在这里的第一个主题,我已经为我的场景尝试了一些解决方案,但没有成功,所以我想我可以使用一些帮助:

我在一个现有的html页面上工作,而且我是实习生,所以我需要在不修改任何其他内容的情况下进行更改(或者至少是最低限度(。

所以我的问题是:

<form action="">
<center>
<div class="example-class">
<input type="text" id="example3" name="fname" value="John"><br>
<input type="text" id="example2" name="lname" value="Doe"><br>
<input type="text" id="example2" name="lname" value="Example"><span>myText</span><br>
<input type="submit" value="Submit">
</div>
</center>
</form> 

在上面的代码中,元素显示为居中。我想添加一些文本,比如";myText"在span标签中,当我单击输入元素右侧的按钮时,但当我尝试这样做时,输入元素会丢失";对齐";其他输入(左起(。那么我该如何添加这个";span文本";但是保持输入元素对齐?

  • 我需要避免更改其他元素css

我附上一个示例代码。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function(){
$("#myText").show();
return false;
})
});
</script> 
</head>
<body>
<style>
input{
width: 92%;
text-align: center;
align: left;
align-items: start;
}
.example-class{
width: 400px;
height:300px;
padding:5%;
}
.myText{
display:none;
}
</style>
<h2>Example</h2>
<form action="">
<center>
<div class="example-class">
<input type="text" id="example3" name="fname" value="John"><br>
<input type="text" id="example2" name="lname" value="Doe"><br>
<input type="text" id="example2" name="lname" value="Example"><span class="myText" id="myText">!!!</span><br>
<button id="button">Show element</button>
<input type="submit" value="Submit">
</div>
</center>
</form> 
</body>
</html>

所以您基本上想在输入值旁边添加myText?

就像你的例子一样,它会变成";示例"在输入框中。

在这种情况下,只需使用javascript。获取当前输入值并将myText附加到其中。

$(document).ready(function() {
$("#button").click(function(){
let myText = '!!!'
let currentValue = $("#example2").val();
$("#example2").val(currentValue + ' ' + myText)
return false;
})
});

//编辑(我更清楚地理解你在评论后想要什么(

您可以在css中使用position: relativeposition: absolute

.example-class{
position:relative;  // add this
width: 400px;
height:300px;
padding:5%;
}
.myText{
display:none;
position:absolute; // add this
right: 80px; // play with this one. 
}

通常情况下,这样就可以了。

将绝对位置设置为您的跨度

$(document).ready(function() {
$("#button").click(function() {
$("#myText").show();
return false;
})
});
input {
width: 92%;
text-align: center;
align: left;
align-items: start;
}
.example-class {
width: 400px;
height: 300px;
padding: 5%;
}
.myText {
display: none;
position: absolute; /*<-- the change */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<h2>Example</h2>
<form action="">
<center>
<div class="example-class">
<input type="text" id="example3" name="fname" value="John"><br>
<input type="text" id="example2" name="lname" value="Doe"><br>
<input type="text" id="example2" name="lname" value="Example"><span class="myText" id="myText">!!!</span><br>
<button id="button">Show element</button>
<input type="submit" value="Submit">
</div>
</center>
</form>