如何在新元素上添加样式并在创建时将其删除

时间:2019-01-05 10:35:05

标签: javascript html css ajax

我有一个JavaScript代码,它是在单击按钮时创建新元素的,我有一个问题。 这是我的JavaScript代码:

class MyAsyncTask extends AsyncTask<Void, Void, List<String>> {
    MyAdapter myAdapter;
    ArrayList<String> values = new ArrayList<>();

    public MyAsyncTask(MyAdapter adapter) {
        this.myAdapter = myAdapter;
    }

    @Override
    protected List<String> doInBackground(String... params) {
        ArrayList<String> result = new ArrayList<>();
        // long operation, for example: get results from url
        return result;
    }

    @Override
    protected void onPostExecute(List<String> list) {
        myAdapter.setNewList(list);
    }
}

class MyAdapter {

    private List<String> list;

    ............

    void setNewList(List<String> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    ............
}

如何向该新元素添加一个样式,该样式只能在创建时播放一次,并且在创建此元素且不再需要此样式时将其删除。

UPD。我的html代码:

var comment = document.querySelector("#AddComment");
var req = new XMLHttpRequest();

if(comment){
    comment.addEventListener("click", function () {
        var csrftok = '{{ csrf_token }}';
        req.open('POST', '{{ request.path }}');
        CommentBlock = {
            "text": comment.previousElementSibling.value,
            //'csrfmiddlewaretoken': csrftok,
        };
        req.setRequestHeader('X-CSRFToken', csrftok);
        req.setRequestHeader("Content-Type", "application/json");
        req.onreadystatechange = function () {
            if(req.readyState == 4) {
                let text = document.createElement('div');
                text.innerHTML = req.responseText;
                let comment_blocks = text.querySelector("#comments").getElementsByClassName("commentblock");
                let new_block = comment_blocks[comment_blocks.length - 1];
                document.querySelector("#comment_addform").before(new_block);
            };
        };
        req.send(JSON.stringify(CommentBlock));
    });
}

1 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,最好的选择是使用CSS动画。

我不确定您要设置动画的元素,但可以说该元素具有“ commentblock”类。如果要制作淡入动画,则CSS代码可能如下所示:

.commentblock {
    animation: custom 1s;
}

@keyframes custom {
    0% {
        display: block;
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}

您可以在此处找到更多详细信息:https://www.w3schools.com/css/css3_animations.asp