Ir ao conteúdo

Posts recomendados

Postado

Olá pessoal,

Estou criando uma sistema para criar automaticamente padrões de box-shadow, acredito que meu código pode ser bem melhorado, mais como estou ainda aprendendo, fico na dúvida de como melhorar ele para não ter tantos códigos repetidos.

 

CÓDIGO

 

$(document).ready(function () {

    const hexToRgb = hex =>
        hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i
            , (m, r, g, b) => '#' + r + r + g + g + b + b)
            .substring(1).match(/.{2}/g)
            .map(x => parseInt(x, 16))

    //QUAIS CAMPOS E ELEMENTOS
    var horizontalLength = $('#horizontal-length');
    var verticalLength = $('#vertical-length');
    var blurRadius = $('#blur-radius');
    var spreedField = $('#spread-field');
    var boxColor = $('#box-color');
    var backgroundColor = $('#background-color');
    var shadowColor = $('#shadow-color');
    var shadowOpacity = $('#shadow-opacity');
    var colorBoxPanel = $('#box-shadow-object');
    var colorBackgroundColor = $('#box-shadow-wrapper');

    //VALOR DOS CAMPOS
    var valHorizontalLength = horizontalLength.val();
    var valVerticalLength = verticalLength.val();
    var valBlurRadius = blurRadius.val();
    var valSpreedField = spreedField.val();
    var valBoxColor = boxColor.val();
    var valBackgroundColor = backgroundColor.val();
    var valShadowColor = shadowColor.val();
    var r = hexToRgb(valShadowColor)[0];
    var g = hexToRgb(valShadowColor)[1];
    var b = hexToRgb(valShadowColor)[2];

    var valShadowOpacity = shadowOpacity.val();
    var shadowBoxPanel = 'rgba(' + r + ',' + g + ',' + b + ', ' + valShadowOpacity + ') ' + valHorizontalLength + 'px ' + valVerticalLength + 'px ' + valBlurRadius + 'px ' + valSpreedField + 'px';
    var inset = $($(this).find('.right-pos')).length == 1;

    //ONDE APLICAR
    colorBoxPanel.css({
        'box-shadow': shadowBoxPanel,
        'background-color': valBoxColor
    });

    colorBackgroundColor.css('background-color', valBackgroundColor);

    //MUDAR CONFORME A COR E ITENS SELECIONADOS

    //SLIDER HORIZONTAL
    $('#slider-horizontal-bs').slider({
        value: 10,
        min: -200,
        max: 200,
        step: 1,
        slide: function (event, ui) {
            $("#horizontal-length").val(ui.value);
            shadowBoxPanel = 'rgba(' + r + ',' + g + ',' + b + ', ' + valShadowOpacity + ') ' + ui.value + 'px ' + valVerticalLength + 'px ' + valBlurRadius + 'px ' + valSpreedField + 'px';
            colorBoxPanel.css('box-shadow', shadowBoxPanel);
        }
    });
    $("#horizontal-length").val($("#slider-horizontal-bs").slider("value"));

    //SLIDER VERTICAL
    $('#slider-vertical-bs').slider({
        value: 10,
        min: -200,
        max: 200,
        step: 1,
        slide: function (event, ui) {
            $("#vertical-length").val(ui.value);
            shadowBoxPanel = 'rgba(' + r + ',' + g + ',' + b + ', ' + valShadowOpacity + ') ' + valHorizontalLength + 'px ' + ui.value + 'px ' + valBlurRadius + 'px ' + valSpreedField + 'px';
            colorBoxPanel.css('box-shadow', shadowBoxPanel);
        }
    });
    $("#vertical-length").val($("#slider-vertical-bs").slider("value"));

    //SLIDER OPACITY
    $('#slider-opacity-bs').slider({
        value: 0.7,
        min: 0,
        max: 1,
        step: 0.01,
        slide: function (event, ui) {
            $("#shadow-opacity").val(ui.value);
            shadowBoxPanel = 'rgba(' + r + ',' + g + ',' + b + ', ' + ui.value + ') ' + valHorizontalLength + 'px ' + valVerticalLength + 'px ' + valBlurRadius + 'px ' + valSpreedField + 'px';
            colorBoxPanel.css('box-shadow', shadowBoxPanel);
        }
    });
    $("#vertical-length").val($("#slider-opacity-bs").slider("value"));

    // INSET BUTTON
    $(".option-panel input").checkboxradio();

    $(".option-panel .option").click(function () {
        var option = $(this).attr('id');

        if (option == 'inset') {
            shadowBoxPanel = 'rgba(' + r + ',' + g + ',' + b + ', ' + valShadowOpacity + ') ' + valHorizontalLength + 'px ' + valVerticalLength + 'px ' + valBlurRadius + 'px ' + valSpreedField + 'px ' + option;
            colorBoxPanel.css('box-shadow', shadowBoxPanel);
        } else {
            shadowBoxPanel = 'rgba(' + r + ',' + g + ',' + b + ', ' + valShadowOpacity + ') ' + valHorizontalLength + 'px ' + valVerticalLength + 'px ' + valBlurRadius + 'px ' + valSpreedField + 'px ';
            colorBoxPanel.css('box-shadow', shadowBoxPanel);
        }
    })


    //COLOR PIKER SPECTRUM
    boxColor.spectrum({
        showInput: true,
        showAlpha: true,
        preferredFormat: "hex",
    });

    backgroundColor.spectrum({
        showInput: true,
        showAlpha: true,
        preferredFormat: "rgb",
    });

    shadowColor.spectrum({
        showInput: true,
        showAlpha: true,
        preferredFormat: "rgb",
    });

    horizontalLength.on('change', function () {
        horizontalLength = $(this).val();
        shadowBoxPanel = valShadowColor + ' ' + horizontalLength + 'px ' + valVerticalLength + 'px ' + valBlurRadius + 'px ' + valSpreedField + 'px';
        colorBoxPanel.css('box-shadow', shadowBoxPanel);
    })

    shadowColor.on('change', function () {
        valShadowColor = $(this).val();
        shadowBoxPanel = valShadowColor + ' ' + valHorizontalLength + 'px ' + valVerticalLength + 'px ' + valBlurRadius + 'px ' + valSpreedField + 'px';
        colorBoxPanel.css('box-shadow', shadowBoxPanel);
    });

    boxColor.on('change', function () {
        boxColor = $(this).val();
        colorBoxPanel.css('background-color', boxColor);
    });

    backgroundColor.on('change', function () {
        backgroundColor = $(this).val();
        colorbackgroundColor.css('background-color', backgroundColor);
    });
});

 

Os inputs

image.png.45b56136a3f5e4bd0db798d8f9f1fe03.png

  • Moderador
Postado

@bigbossbr Não tem muito o que melhorar aí. 

Talvez você possa transformar tudo isso em um plugin jQuery que usa os outros plugins como spectrum e slider como dependentes.

Postado

@DiF Então, estou analisando agora o código e algo que esta me deixando um pouco preocupado é ter muitas partes iguais, ai fico imaginando como da para criar algumas funções para receber determinadas informações iguais, para chamar depois, por exemplo:

 

Como diminuir este código, tendo em vida que as configurações do plugin spectrum é iguais para todas as chamadas?

 

//COLOR PIKER SPECTRUM
    boxColor.spectrum({
        showInput: true,
        showAlpha: true,
        preferredFormat: "rgb",
        move: function (color) {
            colorBoxPanel.css('background-color', color.toHexString());
        }
    });

    backgroundColor.spectrum({
        showInput: true,
        showAlpha: true,
        preferredFormat: "rgb",
        move: function (color) {
            colorBackgroundColor.css('background-color', color.toHexString());
        }
    });

    shadowColor.spectrum({
        showInput: true,
        showAlpha: true,
        preferredFormat: "rgb",
        move: function (color) {
            r = hexToRgb(color.toHexString())[0];
            g = hexToRgb(color.toHexString())[1];
            b = hexToRgb(color.toHexString())[2];

            shadowBoxPanel = 'rgba(' + r + ',' + g + ',' + b + ', ' + valShadowOpacity + ') ' + valHorizontalLength + 'px ' + valVerticalLength + 'px ' + valBlurRadius + 'px ' + valSpreedField + 'px ';
            colorBoxPanel.css('box-shadow', shadowBoxPanel);
            console.log(shadowBoxPanel)
        }
    });

 

Outra situação que notei, foi que, quando eu atualizo um dos itens, ao modificar outro, o antigo é zerado, a variável não esta ficando com o novo valor, estranho

Algum valores joguei em um arrays, não sei se é a melhor forma, mais foi o que pensei no momento, assim todas as configurações que este plugin tiver, jogo no mesmo arrays evitando replicar o código

 

const optionsSpectrum = [
        {
            showInput: true,
            showAlpha: true,
            preferredFormat: "rgb"
        }
    ]

 

Postado

Eu poderia fazer mais se tivesse o código em HTML também. :D

 

Mas vou falar um pouco sobre o Spectrum, acho que você pode fazer da seguinte forma:

 

HTML:


<input type='text' class="colorpicker" id="boxColor"/>
<input type='text' class="colorpicker" id="backgroundColor"/>
<input type='text' class="colorpicker" id="shadowColor"/>

 

JS:

const cores = {
  boxColor: '',
  backgroundColor: '',
  shadowColor: ''
}

$(".colorpicker").spectrum({
  showInput: true,
  showAlpha: true,
  preferredFormat: "rgb",
  change: function(color) {
	// Se você n mudar para Hex o rgb pode acabar retornando um objeto um pouco grande... você quem sabe. :D 
    cores[($(this).attr('id'))] = color.toHexString()
    console.log(cores)
  }
})

 

 

Os 3 inputs vão funcionar, e pela ID deles você consegue alterar os valores de cores e salvar a cor separadamente entre os 3.

 

 

Normalmente eu mando o link do CodePen para mostrar o código funcionando, mas o Spectrum não funciona de forma alguma, tentei pelo JSFiddle e CodePen, de qualquer forma, aqui tá o link:

https://jsfiddle.net/RuiGuilherme/j3xdwtvc/1/

https://codepen.io/ruiguilherme/pen/ExNBLba?editors=1011

 

  • Curtir 1
Postado

@Rui Guilherme Opa Rui, obrigado pela dica, estou aprendendo muito com todos estes materiais que estou desenvolvendo. Vou colocar o HTML aqui para ajudar.

 

<!DOCTYPE html>
<html lang="pt-br">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="./img/css.svg" sizes="16x16 32x32" type="image/png">
    <title>CSS Generator - Border Radius/Noise Texture/Box Shadow/Gradiente Generator</title>

    <!-- STYLES CSS -->
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <link href='https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/css/all.css' rel='stylesheet'>
    <link rel="stylesheet" type="text/css"
        href="https://cdn.jsdelivr.net/npm/spectrum-colorpicker2/dist/spectrum.min.css">

    <link type="text/css" rel="stylesheet" href="./css/all.css">
</head>

<body>

    <div class="container mt-3">

        <!-- NAVEGAÇÃO -->
        <nav class="navbar navbar-light bg-light">
            <a href="#" class="navbar-brand">
                <img src="./img/css.svg" width="30" height="30" alt="">
                CSS Generator
            </a>
            <ul class="nav  nav-pills">
                <li class="nav-item"><a class="nav-link" href="#">Box Shadow</a></li>
                <li class="nav-item"><a class="nav-link" href="#">Gradient</a></li>
                <li class="nav-item"><a class="nav-link" href="#">Border Radius</a></li>
                <li class="nav-item"><a class="nav-link" href="#">Lorem Ipsum</a></li>
                <li class="nav-item"><a class="nav-link" href="#">Lorem Ipsum IMG</a></li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
                        data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        <i class="faz fa-bars"></i>
                    </a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                        <a class="dropdown-item" href="#">Ação</a>
                        <a class="dropdown-item" href="#">Outra ação</a>
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" href="#">Algo mais aqui</a>
                    </div>
                </li>
            </ul>
        </nav>
        <div class="row justify-content-center mt-2 mb-3">
            <div class="banner ">
                <img src="holder.js/728x90?theme=gray">
            </div>
        </div>

        <!-- CONTEÚDO PRINCIPAL -->
        <div class="row">
            <div class="col-sm-4">
                <div class="card">
                    <div class="card-header title">
                        Configurações
                    </div>
                    <div class="card-body">
                        <!-- CONFIG HORIZONTAL LENGTH -->
                        <div class="block-config">
                            <div class="row">
                                <label for="horizontal-length">Tamanho Horizontal</label>
                                <label class="align-right" for="horizontal-length">px</label>
                                <div class="text-1">
                                    <input id="horizontal-length" type="text" value="10">
                                </div>
                            </div>
                            <div id="slider-horizontal-bs"
                                class="slider-bar large ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all">
                                <a class="ui-slider-handle ui-state-default ui-corner-all" href="#"
                                    style="left: 21.5%;"></a>
                            </div>
                            <!-- CONFIG VERTICAL LENGTH -->
                            <div class="row mtop15">
                                <label for="vertical-length">Tamanho Vertical</label>
                                <label class="align-right" for="vertical-length">px</label>
                                <div class="text-1">
                                    <input id="vertical-length" type="text" value="10">
                                </div>
                            </div>
                            <div id="slider-vertical-bs"
                                class="slider-bar large ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all">
                                <a class="ui-slider-handle ui-state-default ui-corner-all" href="#"
                                    style="left: 52.5%;"></a>
                            </div>
                        </div>
                        <!-- CONFIG BLUR RADIUS -->
                        <div class="block-config">
                            <div class="row">
                                <label for="blur-radius">Propriedade Blur Radius</label>
                                <label class="align-right" for="blur-radius">px</label>
                                <div class="text-1">
                                    <input id="blur-radius" type="text" value="5">
                                </div>
                            </div>
                            <div id="slider-blur-bs"
                                class="slider-bar large ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all">
                                <a class="ui-slider-handle ui-state-default ui-corner-all" href="#"
                                    style="left: 3.33333%;"></a>
                            </div>
                            <!-- CONFIG BLUR RADIUS SPREAD RADIUS-->
                            <div class="row mtop15">
                                <label for="spread-field">Tamanho do Raio</label>
                                <label class="align-right" for="spread-field">px</label>
                                <div class="text-1">
                                    <input id="spread-field" type="text" value="0">
                                </div>
                            </div>
                            <div id="slider-spread-field"
                                class="row-s slider-bar large ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all">
                                <a class="ui-slider-handle ui-state-default ui-corner-all" href="#"
                                    style="left: 50%;"></a>
                            </div>
                        </div>
                        <!-- CONFIG SHADOW COLOR -->
                        <div class="block-config">
                            <div class="row color-row">
                                <label for="shadow-color">Cor da Sombra</label>
                                <div class="text-2">
                                    <input id="shadow-color" type="text" value="#08713c">
                                </div>
                            </div>
                        </div>
                        <!-- CONFIG BACKGROUND COLOR -->
                        <div class="block-config">
                            <div class="row color-row">
                                <label for="background-color">Cor do Background</label>
                                <div class="text-2">
                                    <input id="background-color" type="text" value="#ffffff">
                                </div>
                            </div>
                        </div>
                        <!-- CONFIG BOX COLOR -->
                        <div class="block-config">
                            <div class="row color-row">
                                <label for="box-color">Box Cor</label>
                                <div class="text-2">
                                    <input id="box-color" type="text" value="#1a6880">
                                </div>
                            </div>
                        </div>
                        <!-- CONFIG OPACITY -->
                        <div class="block-config">
                            <div class="row">
                                <label for="shadow-opacity">Opacidade</label>
                                <div class="text-1">
                                    <input id="shadow-opacity" type="text" value="0.75">
                                </div>
                            </div>

                            <div id="slider-opacity-bs"
                                class="slider-bar large ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all">
                                <a class="ui-slider-handle ui-state-default ui-corner-all" href="#"
                                    style="left: 70%;"></a>
                            </div>
                        </div>
                        <!-- CONFIG OUTLINE E INSET -->
                        <div class="block-config">
                            <div class="option-panel">
                                <fieldset>
                                    <label for="outline"
                                        class="ui-checkboxradio-label ui-corner-all ui-button ui-widget ui-checkboxradio-radio-label">Outline</label>
                                    <input type="radio" name="option" id="outline"
                                        class="ui-checkboxradio ui-helper-hidden-accessible option">
                                    <label for="inset"
                                        class="ui-checkboxradio-label ui-corner-all ui-button ui-widget ui-checkboxradio-radio-label">Inset</label>
                                    <input type="radio" name="option" id="inset"
                                        class="ui-checkboxradio ui-helper-hidden-accessible option">
                                </fieldset>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-sm-8">
                <div class="card">
                    <div class="card-header title">
                        Resultado
                    </div>
                    <div class="card-body">
                        <div id="box-shadow-wrapper" class="right-column" style="background-color: rgb(255, 255, 255);">
                            <div class="box-wrap">
                                <div id="box-shadow-code" class="content">
                                    <div>-webkit-box-shadow: -9px -5px 5px 0px rgba(0,0,0,0.75);</div>
                                    <div>-moz-box-shadow: -9px -5px 5px 0px rgba(0,0,0,0.75);</div>
                                    <div>box-shadow: -9px -5px 5px 0px rgba(0,0,0,0.75);</div>
                                </div>

                                <div id="box-shadow-panel">
                                    <div id="box-shadow-object">
                                        <a id="copy-text-input" class="btn-link-1" href="javascript:;">Copiar Código</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
        <div class="row justify-content-center mt-5 mb-3">
            <div class="banner ">
                <img src="holder.js/728x90?theme=gray">
            </div>
        </div>
        <!-- FOOTER -->
        <div class="row">
            <footer class="container py-5">
                <div class="row border-top pt-3">
                    <div class="col-12 col-md">
                        <a href="#" class="navbar-brand">
                            <img src="./img/css.svg" width="30" height="30" alt="">
                            CSS Generator
                        </a>
                        <small class="d-block mb-3 text-muted">© 2021</small>
                    </div>
                    <div class="col-6 col-md">
                        <h5>Features</h5>
                        <ul class="list-unstyled text-small">
                            <li><a class="text-muted" href="#">Algo legal</a></li>
                            <li><a class="text-muted" href="#">Feature aleatória</a></li>
                            <li><a class="text-muted" href="#">Recursos para times</a></li>
                            <li><a class="text-muted" href="#">Coisas para desenvolvedores</a></li>
                            <li><a class="text-muted" href="#">Outra coisa legal</a></li>
                            <li><a class="text-muted" href="#">Último item</a></li>
                        </ul>
                    </div>
                    <div class="col-6 col-md">
                        <h5>Fontes</h5>
                        <ul class="list-unstyled text-small">
                            <li><a class="text-muted" href="#">Fonte</a></li>
                            <li><a class="text-muted" href="#">Nome da fonte</a></li>
                            <li><a class="text-muted" href="#">Outra fonte</a></li>
                            <li><a class="text-muted" href="#">Fonte final</a></li>
                        </ul>
                    </div>
                    <div class="col-6 col-md">
                        <h5>Fontes</h5>
                        <ul class="list-unstyled text-small">
                            <li><a class="text-muted" href="#">Negócios</a></li>
                            <li><a class="text-muted" href="#">Educação</a></li>
                            <li><a class="text-muted" href="#">Governo</a></li>
                            <li><a class="text-muted" href="#">Jogos</a></li>
                        </ul>
                    </div>
                    <div class="col-6 col-md">
                        <h5>Sobre</h5>
                        <ul class="list-unstyled text-small">
                            <li><a class="text-muted" href="#">Equipe</a></li>
                            <li><a class="text-muted" href="#">Locais</a></li>
                            <li><a class="text-muted" href="#">Privacidade</a></li>
                            <li><a class="text-muted" href="#">Termos</a></li>
                        </ul>
                    </div>
                </div>
            </footer>
        </div>
    </div>

    <!-- SCRIPTS JS -->
    <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/spectrum-colorpicker2/dist/spectrum.min.js"></script>

    <script src="./js/box-shadow.js"></script>
    <script src="./js/holder.js"></script>
    <script src="./js/script.js"></script>
</body>

</html>

 

Postado

Efetuei algumas melhorias no código afim de deixá-lo menos repetitivo, porém ainda não consegui entender o porque as informações estão sendo resetadas a cada input que pe modificado. Onde estou me perdendo?

 

$(document).ready(function () {

    const hexToRGB = (hex, alpha) => {
        var r = parseInt(hex.slice(1, 3), 16),
            g = parseInt(hex.slice(3, 5), 16),
            b = parseInt(hex.slice(5, 7), 16);

        if (alpha) {
            return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")";
        } else {
            return "rgb(" + r + ", " + g + ", " + b + ")";
        }
    }

    const colorInti = (color, op, hl, vl, br, sf, i = '') => {
        return hexToRGB(color, op) + ' ' + hl + 'px ' + vl + 'px ' + br + 'px ' + sf + 'px ' + i;
    }

    //QUAIS CAMPOS E ELEMENTOS
    const horizontalLength = $('#horizontal-length');
    const verticalLength = $('#vertical-length');
    const blurRadius = $('#blur-radius');
    const spreedField = $('#spread-field');
    const boxColor = $('#box-color');
    const backgroundColor = $('#background-color');
    const shadowColor = $('#shadow-color');
    const shadowOpacity = $('#shadow-opacity');
    const colorBoxPanel = $('#box-shadow-object');
    const colorBackgroundColor = $('#box-shadow-wrapper');

    //VALOR DOS CAMPOS
    var valHorizontalLength = horizontalLength.val();
    var valVerticalLength = verticalLength.val();
    var valBlurRadius = blurRadius.val();
    var valSpreedField = spreedField.val();
    var valBoxColor = boxColor.val();
    var valBackgroundColor = backgroundColor.val();
    var valShadowColor = shadowColor.val();
    var valShadowOpacity = shadowOpacity.val();
    var shadowBoxPanel;
    var inset;

    // INSET BUTTON
    $(".option-panel input").checkboxradio();

    $(".option-panel .option").click(function () {
        var option = $(this).attr('id');

        inset = option == 'inset' ? 'inset' : 'outline';
    })


    //SLIDERS
    $('.slider-bar').slider({
        value: 10,
        min: -200,
        max: 200,
        step: 1,
        slide: function (event, ui) {

            let selected = $(this).attr('id');

            if (selected == 'slider-horizontal-bs') {
                $("#horizontal-length").val(ui.value);
                colorBoxPanel.css('box-shadow', colorInti(valShadowColor, valShadowOpacity, ui.value, valVerticalLength, valBlurRadius, valSpreedField, inset));
            } else if (selected == 'slider-vertical-bs') {
                $("#vertical-length").val(ui.value);
                colorBoxPanel.css('box-shadow', colorInti(valShadowColor, valShadowOpacity, valHorizontalLength, ui.value, valBlurRadius, valSpreedField, inset));
            } else if (selected == 'slider-blur-bs') {
                $("#shadow-opacity").val(ui.value);
                colorBoxPanel.css('box-shadow', colorInti(valShadowColor, valShadowOpacity, valHorizontalLength, valVerticalLength, ui.value, valSpreedField, inset));
            } else if (selected == 'slider-spread-field') {
                $("#shadow-opacity").val(ui.value);
                colorBoxPanel.css('box-shadow', colorInti(valShadowColor, valShadowOpacity, valHorizontalLength, valVerticalLength, valBlurRadius, ui.value, inset));
            }
        }
    });

    //SOMENTE PARA CASO DO SLIDER DE OPACITY
    $('#slider-opacity-bs').slider({
        value: 0.7,
        min: 0,
        max: 1,
        step: 0.01,
        slide: function (event, ui) {
            $("#shadow-opacity").val(ui.value);
            colorBoxPanel.css('box-shadow', colorInti(valShadowColor, ui.value, valHorizontalLength, valVerticalLength, valBlurRadius, valSpreedField, inset));
        }
    });

    const optionsSpectrum =
    {
        showInput: true,
        showAlpha: true,
        preferredFormat: "rgb"
    }

    const cores = {
        boxColor: '',
        backgroundColor: '',
        shadowColor: ''
    }

    $(".colorpicker").spectrum({
        optionsSpectrum,
        move: function (color) {
            let selected = $(this).attr('id');
            const colorEl = () => cores[($(this).attr('id'))] = hexToRGB(color.toHexString(), color['_a']);

            console.log(selected)

            if (selected == 'box-color') {
                colorBoxPanel.css('background-color', colorEl());

            } else if (selected == 'shadow-color') {
                shadowBoxPanel = colorEl() + ' ' + valHorizontalLength + 'px ' + valVerticalLength + 'px ' + valBlurRadius + 'px ' + valSpreedField + 'px ';
                colorBoxPanel.css('box-shadow', shadowBoxPanel);

            } else if (selected == 'background-color') {
                colorBackgroundColor.css('background-color', colorEl());

            }
        }
    })
    colorInti(valShadowColor, valShadowOpacity, valHorizontalLength, valVerticalLength, valBlurRadius, valSpreedField, inset);
});

 

Postado

Efetuei algumas melhorias no código afim de deixá-lo menos repetitivo, e acredito que esta tudo funcionando. Se tiverem alguma sugestão, sempre é bem vinda.

 

$(document).ready(function () {

    const hexToRGB = (hex, alpha) => {
        var r = parseInt(hex.slice(1, 3), 16),
            g = parseInt(hex.slice(3, 5), 16),
            b = parseInt(hex.slice(5, 7), 16);

        if (alpha) {
            return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")";
        } else {
            return "rgb(" + r + ", " + g + ", " + b + ")";
        }
    }

    const colorInti = (color, op, hl, vl, br, sf, i = '') => {
        return hexToRGB(color, op) + ' ' + hl + 'px ' + vl + 'px ' + br + 'px ' + sf + 'px ' + i;
    }

    //QUAIS CAMPOS E ELEMENTOS
    const horizontalLength = $('#horizontal-length');
    const verticalLength = $('#vertical-length');
    const blurRadius = $('#blur-radius');
    const spreedField = $('#spread-field');
    const boxColor = $('#box-color');
    const backgroundColor = $('#background-color');
    const shadowColor = $('#shadow-color');
    const shadowOpacity = $('#shadow-opacity');
    const colorBoxPanel = $('#box-shadow-object');
    const colorBackgroundColor = $('#box-shadow-wrapper');
    const boxCode = $('#box-shadow-code');

    //VALOR DOS CAMPOS
    var valHorizontalLength = horizontalLength.val();
    var valVerticalLength = verticalLength.val();
    var valBlurRadius = blurRadius.val();
    var valSpreedField = spreedField.val();
    var valBoxColor = boxColor.val();
    var valBackgroundColor = backgroundColor.val();
    var valShadowColor = shadowColor.val();
    var valShadowOpacity = shadowOpacity.val();
    var tab = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
    var shadowBoxPanel;
    var inset;

    // INSET BUTTON
    $(".option-panel input").checkboxradio();
    $(".option-panel .option").click(function () {
        var option = $(this).attr('id');
        inset = option == 'inset' ? 'inset' : '';
        updateShadow();
        codeUpdate();
    })


    //SLIDERS
    $('.slider-bar').slider({
        value: 10,
        min: -200,
        max: 200,
        step: 1,
        slide: function (event, ui) {

            let selected = $(this).attr('id');

            if (selected == 'slider-horizontal-bs') {
                $("#horizontal-length").val(ui.value);
                valHorizontalLength = ui.value;
                colorBoxPanel.css('box-shadow', colorInti(valShadowColor, valShadowOpacity, valHorizontalLength, valVerticalLength, valBlurRadius, valSpreedField, inset));
            } else if (selected == 'slider-vertical-bs') {
                $("#vertical-length").val(ui.value);
                valVerticalLength = ui.value;
                colorBoxPanel.css('box-shadow', colorInti(valShadowColor, valShadowOpacity, valHorizontalLength, valVerticalLength, valBlurRadius, valSpreedField, inset));
            } else if (selected == 'slider-spread-field') {
                $("#spread-field").val(ui.value);
                valSpreedField = ui.value;
                colorBoxPanel.css('box-shadow', colorInti(valShadowColor, valShadowOpacity, valHorizontalLength, valVerticalLength, valBlurRadius, valSpreedField, inset));
            }
            codeUpdate();
        }
    });

    //SOMENTE PARA CASO DO SLIDER DE OPACITY
    $('#slider-opacity-bs').slider({
        value: 0.7,
        min: 0,
        max: 1,
        step: 0.01,
        slide: function (event, ui) {
            $("#shadow-opacity").val(ui.value);
            valShadowOpacity = ui.value;
            colorBoxPanel.css('box-shadow', colorInti(valShadowColor, valShadowOpacity, valHorizontalLength, valVerticalLength, valBlurRadius, valSpreedField, inset));
            codeUpdate();
        }
    });

    //SOMENTE PARA CASO DO SLIDER BLUR RADIUS
    $('#slider-blur-bs').slider({
        value: 50,
        min: 0,
        max: 300,
        step: 1,
        slide: function (event, ui) {
            $("#blur-radius").val(ui.value);
            valBlurRadius = ui.value;
            colorBoxPanel.css('box-shadow', colorInti(valShadowColor, valShadowOpacity, valHorizontalLength, valVerticalLength, valBlurRadius, valSpreedField, inset));
            codeUpdate();
        }
    });

    const optionsSpectrum =
    {
        showInput: true,
        showAlpha: true,
        preferredFormat: "rgb"
    }

    const cores = {
        boxColor: '',
        backgroundColor: '',
        shadowColor: ''
    }

    $(".colorpicker").spectrum({
        optionsSpectrum,
        move: function (color) {
            let selected = $(this).attr('id');
            const colorEl = () => cores[($(this).attr('id'))] = hexToRGB(color.toHexString(), color['_a']);

            if (selected == 'box-color') {
                valBoxColor = colorEl();
                colorBoxPanel.css('background-color', valBoxColor);
                codeUpdate();
            } else if (selected == 'shadow-color') {
                valShadowColor = color.toHexString();
                valShadowOpacity = color['_a'];
                shadowBoxPanel = colorInti(valShadowColor, valShadowOpacity, valHorizontalLength, valVerticalLength, valBlurRadius, valSpreedField, inset);
                colorBoxPanel.css('box-shadow', shadowBoxPanel);
                codeUpdate();
            } else if (selected == 'background-color') {
                valBackgroundColor = colorEl();
                colorBackgroundColor.css('background-color', valBackgroundColor);
                codeUpdate();
            }
        }
    })

    const codeUpdate = () => {

        if (valBoxColor) {
            valBoxColor = valBoxColor;
        }
        boxCode.html(
            '<span class=text-danger>.sua-classe</span> {' +
            '<div>' + tab + 'background-color: ' + valBoxColor + ';</div>\n' +
            '<div>' + tab + '<i>-webkit-box-shadow: ' + colorInti(valShadowColor, valShadowOpacity, valHorizontalLength, valVerticalLength, valBlurRadius, valSpreedField, inset) + ';</div>\n' +
            '<div>' + tab + '-moz-box-shadow: ' + colorInti(valShadowColor, valShadowOpacity, valHorizontalLength, valVerticalLength, valBlurRadius, valSpreedField, inset) + ';</div>\n' +
            '<div>' + tab + 'box-shadow: ' + colorInti(valShadowColor, valShadowOpacity, valHorizontalLength, valVerticalLength, valBlurRadius, valSpreedField, inset) + ';</div>\n' +
            '</i>}'
        );
    }
    const updateShadow = () => {
        colorBoxPanel.css({
            '-webkit-box-shadow': colorInti(valShadowColor, valShadowOpacity, valHorizontalLength, valVerticalLength, valBlurRadius, valSpreedField, inset),
            '-moz-box-shadow': colorInti(valShadowColor, valShadowOpacity, valHorizontalLength, valVerticalLength, valBlurRadius, valSpreedField, inset),
            'box-shadow': colorInti(valShadowColor, valShadowOpacity, valHorizontalLength, valVerticalLength, valBlurRadius, valSpreedField, inset),
            'background-color': valBoxColor
        })
    }
    updateShadow();
    codeUpdate();

    //FUNÇÃO PARA COPIAR O CÓDIGO CRIADO
    $('#copy-code').click(function () {

        var txt = $('#box-shadow-code').text();
        txt = txt.replace('               ', '');
        txt = txt.replace('               ', '');
        txt = txt.replace('               ', '');
        txt = txt.replace('               ', '');
        $('body').append('<textarea id="copied">');
        $('#copied').html(txt);
        $('#copied').select();

        var ok = document.execCommand('copy');
        $('#copied').remove();
        if (ok) {
            $('#modalAlertCodCopied').modal('show');
        }
    });
});

 

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...