【问题标题】:set sweetalert2 width auto according to text message根据短信设置 sweetalert2 宽度自动
【发布时间】:2022-01-13 17:03:17
【问题描述】:

我正在使用 sweetalert2 库来显示基本的警报消息,但有些消息比其他消息更广泛。

可以将alert容器的witdh设置为auto,这样消息就可以一行固定了?

作为默认行为,我认为宽度设置为 360px,但我需要一种解决方法来使其自动...希望有人可以帮助我...谢谢

PD:如果重要的话,我使用的是 Symfony 4.4。默认配置为:

const Toast = Swal.mixin({
    toast: true,
    position: 'top',
    showConfirmButton: false,
    timer: 3000,
    timerProgressBar: true,
});

以及模板中的fire事件:

<script>
    {% for type, msgs in app.session.flashBag.all() %}
        {% for msg in msgs %}
            Toast.fire({
                icon: '{{ type }}',
                title: '{{ msg }}'
            });
       {% endfor %}
    {% endfor %}
</script>

【问题讨论】:

    标签: javascript css sweetalert2


    【解决方案1】:

    经过一些研究但没有运气,尝试和错误是获得适当解决方案的最佳方法。

    首先,覆盖 sweetalert2 库中的一些 css 样式:

    .swal2-container {
        padding: 0.4em;
    }
    
    .swal2-toast {
        max-width: inherit;
    }
    
    body.swal2-toast-shown .swal2-container {
        width: unset;
    }
    
    .swal2-popup.swal2-toast .swal2-title {
        margin: 9px 5px auto;
    }
    

    然后,在脚本标签中创建一个画布元素并使用字体样式计算画布的宽度...

    <script>
            {% for type, msgs in app.session.flashBag.all() %}
            {% for msg in msgs %}
    
            inputText = '{{ msg }}';
            font = "0.875rem Nimrod MT";
    
            canvas = document.createElement("canvas");
            context = canvas.getContext("2d");
            context.font = font;
            width = context.measureText(inputText).width;
            formattedWidth = Math.ceil(width) + 100;
    
            Toast.fire({
                icon: '{{ type }}',
                title: '{{ msg }}',
                width: formattedWidth,
            });
    
            {% endfor %}
            {% endfor %}
        </script>
    

    最终结果:

    希望此解决方案对其他人有所帮助...

    【讨论】:

      猜你喜欢
      • 2014-03-06
      • 2013-06-29
      • 1970-01-01
      • 2012-06-25
      • 2014-07-27
      • 2019-02-28
      • 2015-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多