sdghkjsd ... ndfgjknk
我想在所有浏览器上支持移动和平板电脑视图上截断单词
我希望能够在输入中输入新值并进行提交而不会更改截断(就像我发现
sdghkjsd ... ndfgjknk
并输入
sdghkjsdghhjdfgjhdjghjdfhghjhgkdfgjnfkdgnjkndfgjknk
并提交它而不会被截断(提交原始,更长的值)
// making the input editable
$(".long-value-input").on("click", function() {
$(this).prop("readonly", "");
$(this).focus();
});
/* For smart phones */
@media screen and (max-width: 600px) {
.field {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
}
/* For tablets */
@media screen and (min-width: 600px) and (max-width: 900px) {
.field {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
}
<input type="text" class="field" value="sdghkjsdghhjdfgjhdjghjdfhghjhgkdfgjnfkdgnjkndfgjknk" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
一种实现选项是通过伪元素对父级的元素,并且最小使用JS来更新该值:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
label {
position: relative;
display: inline-flex;
--padding: 8px;
--border-width: 1px;
--offset: calc(var(--padding) + var(--border-width));
font-family: sans-serif;
font-size: 14px;
&:before,
&:after {
content: attr(data-value);
position: absolute;
top: 50%;
translate: 0 -50%;
pointer-events: none;
width: calc(50% - var(--offset));
white-space: nowrap;
overflow: hidden;
}
&:before {
left: var(--offset);
mask-image: linear-gradient(
to right,
#000,
#000 calc(100% - 16px),
transparent
);
}
&:after {
right: var(--offset);
direction: rtl;
text-overflow: ellipsis;
}
&:has(input:focus) {
&:before,
&:after {
opacity: 0;
}
}
}
input {
height: 40px;
padding: 0 var(--padding);
border: solid var(--border-width) #ccc;
font: inherit;
&:not(:focus) {
color: transparent;
}
}
<label
aria-label="Wallet"
data-value="sdghkjsdghhjdfgjhdjghjdfhghjhgkdfgjnfkdgnjkndfgjknk"
>
<input
type="text"
value="sdghkjsdghhjdfgjhdjghjdfhghjhgkdfgjnfkdgnjkndfgjknk"
oninput="this.parentNode.setAttribute('data-value', this.value)"
/>
</label>